Socket.io multiple chats on one page

I want to implement multiple chat windows on one page (like facebook for example). Currently using "numbers", simplified code:

[customer]

socket.emit('join', 'room1');
socket.emit('join', 'room2');

      

[server]

socket.on('join', function(room)
{
    socket.join(room);
});

      

therefore, each separate room on the client is a separate class that handles the chat logic, it should receive events from the server only for the connected room. But if it is one page, then one socket connection is used, so if one socket will connect to multiple rooms and then subscribe to one room, they will also receive events from the other room. How do I separate it?

I am thinking about these paths:

  • Forcing a new socket for each room (so 10 chats = 10 sockets) I think this is not good, due to the high load (if I am wrong, please correct me).
  • Prefix for client events, for example, if I want to handle events for a specific room, I will subscribe like this:

[customer]

var room = 'room1';
socket.on(room + '.new_message', function()
{
    // append message to chat
});

      

[server]

io.sockets.in('room1').emit('room1.new_message', 'some message');

      

Is this a good idea?

If there are other ways to do it, please share with me.

+3


source to share


2 answers


One plug in one room, no problem with multiple jacks.



0


source


I think you are only creating one socket to connect to the server. But one socket can join a multi-room room. When the server is sent to the client, you must define the sending of the number. example: socket.broadcast.to (room) .emit (..... {data: idRoom}) ;. When the client receives a socket from the server. it must determine that popUp will receive the message. You can use idRoom from the server to determine if the PopUp is received.
sorry for my English



-1


source







All Articles