socket.io multiple chats on one page

点点圈 提交于 2019-12-10 20:23:50

问题


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

[client]

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

[server]

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

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

I'm thinking about these ways:

  1. Force new socket connection for each room (so 10 chats = 10 sockets), I think it is not good idea, because of highload (if I'm not right, please correct me)
  2. Prefix for client events, e.g if I want to handle events for specific room I will subscribe like this:

[client]

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 it is other ways to do it, please share with me.


回答1:


One socket one room, no problem about having multiple sockets on.




回答2:


I think you only create one socket to connect to server. But one socket can join multi room. When server send to client, you must determine room send. example: socket.broadcast.to(room).emit(.....{data: idRoom});. When client receive socket from server. it must determine popUp will receive message. You can use idRoom from Server to determine PopUp receive.
Sorry for my English



来源:https://stackoverflow.com/questions/25411481/socket-io-multiple-chats-on-one-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!