Reputation: 30131
I've been trying this for a couple of days now but I can't seem to wrap my head around this. My problem essentially lies with the fact if I have 2 browsers requesting at the same time, my server-side socketio response will return the wrong results to the wrong browser requesting (the results get swapped). I think my problem is that I don't know how does socket.io determines which browser to return the results to. The current code has lotsa moving parts and it'll be a pain to strip to manner that people can find meaningful so instead, I think I will be able to resolve my bug if someone can help me work through and understand the django_chat example found at https://github.com/abourget/gevent-socketio/tree/master/examples/django_chat. So here goes:
So sequentially, when a user enters something into chat, this code fires
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
The socket.emit
function then triggers this function in the ChatNameSpace
class:
def on_user_message(self, msg):
self.log('User message: {0}'.format(msg))
self.emit_to_room(self.room, 'msg_to_room',
self.socket.session['nickname'], msg)
return True
Which in turn calls this emit_to_room
function found in the RoomsMixin class
def emit_to_room(self, room, event, *args):
"""This is sent to all in the room (in this particular Namespace)"""
pkt = dict(type="event",
name=event,
args=args,
endpoint=self.ns_name)
room_name = self._get_room_name(room)
for sessid, socket in self.socket.server.sockets.iteritems():
if 'rooms' not in socket.session:
continue
if room_name in socket.session['rooms'] and self.socket != socket:
socket.send_packet(pkt)
I understand that when a user joins a chat room, the [rooms]
session gets updated with the chatroom he belongs to. It looks something like ['/chat_1', '/chat_2']
where the numbers signify the primary key of the room object.
This is where I get lost. Where does this distinction of specific chatrooms meet the frontend js code? How does the emit function know where to send the response to which room?
Upvotes: 1
Views: 213