Is it possible to receive message from one web socket even though the web socket connection is closed?
I am learning Django Channels and trying to implement WhatsApp like feature. I want to update the contact box of a particular user with latest message even though that particular WebSocket connection is not open
I am using Django channels and each window ( mowdin & jack ) represents a individual web socket connection with that user.
When the connection is open with mowdin and mowdin sends a message, I'm able to update that message in the contact box of mowdin. ( As highlighted in image above).
consumers.py
class PersonalChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
print('Line 8 Connect',self.scope['user'])
self.my_id = self.scope['user'].id
self.other_user_id = self.scope['url_route']['kwargs']['id']
if int(self.my_id) > int(self.other_user_id):
self.room_name = f'{self.my_id}-{self.other_user_id}'
else:
self.room_name = f'{self.other_user_id}-{self.my_id}'
self.room_group_name = 'chat_%s' %self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name,
)
await self.accept()
async def disconnect(self, code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data=None, bytes_data=None):
data = json.loads(text_data)
message = data['message']
sender_username = data['sender']
group = await database_sync_to_async(Group.objects.get)(name=self.room_group_name)
receiving_user = await database_sync_to_async(User.objects.get)(id=self.other_user_id)
group.last_message = message
group.sent_by = self.scope['user'].username
group.received_by = receiving_user.username
await database_sync_to_async(group.save)()
chat = Chat(message=message, group=group, user=self.scope['user'])
await self.channel_layer.group_send(
self.room_group_name,
{
'type':'chat.message',
'message': message,
'sender':sender_username,
'group':self.room_group_name,
}
)
async def chat_message(self, event):
print('Line 52 Sending Message',self.scope['user'], event)
message = event['message']
username = event['sender']
group = event['group']
await self.send(text_data=json.dumps({
'message':message,
'username':username,
'group':group,
}))
index.html
<tbody>
{% for user, chat, group in user_chats %}
<tr>
<table class="table table-hover">
<tbody>
<tr>
<td rowspan="2"><img src="{% static 'assets/dp.png' %}" alt="" class="profile-image rounded-circle"></td>
<td><a href="{% url 'chat_app:chat' id=user.id %}">{{user.username}}</a></td>
</tr>
<tr>
<td id="{{group}}">
{% if chat %}
{{chat}}
{% else %}
{% endif %}
</td>
</tr>
</tbody>
</table>
</tr>
{% endfor %}
</tbody>
Corresponding JS Code:
const id = JSON.parse(document.getElementById('json-username').textContent);
const sender_username = JSON.parse(document.getElementById('json-message-username').textContent);
const socket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/'
+ id
+ '/'
);
socket.onmessage = function(e) {
console.log(e)
const data = JSON.parse(e.data)
console.log('Line 28 chat.js RECEIVED MESSAGE ',data)
date_obj = new Date()
time_hours = date_obj.getHours()
time_minutes = date_obj.getMinutes()
if (time_hours < 10 ){
time_hours = '0' + time_hours
}
if (time_minutes < 10 ){
time_minutes = '0' + time_minutes
}
time = time_hours+':'+time_minutes
const curr_group = document.getElementById(data.group)
console.log('Group is :',curr_group)
var chat_box_msg = data.message
if (data.username == sender_username)
{
var cbm = 'You : ' + chat_box_msg
console.log('Line 54 chat.js',cbm)
curr_group. innerHTML = cbm
document.getElementById('chat-body'). innerHTML += `
<tr>
<td>
<p class="bg-success p-2 mt-2 mr-5 shadow-sm text-white float-right rounded">
${data.message}
</p>
</td>
<td>
<p><small class="p-1 shadow-sm">${time}</small>
</p>
</td>
</tr>
`
}
But at the same time, when Jack sends a message, I am not able to update the message sent by Jack in his contact box as the WebSocket connection with Jack is not yet open. Is there any way I can achieve this ?
I want to achieve the below ( Image taken from WhatsApp ):
Even though connection with Yusuf is not open, message sent by him is updated.
