最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Join multiple rooms at once Socket.io - Stack Overflow

programmeradmin0浏览0评论

I have an application where a user can get a list of chat rooms they are in, they can then click into any specific chat room they want. Currently the socket joins the room when the user clicks into a specific room and the socket leaves the room when the user goes back to the main list of chat rooms. This means that when the user is on the chat list page their socket is not in any rooms (bar the default room that the connection event makes) and thus new messages are not pushed to them in real time when on this page.

I plan that when the user loads the chat list page, they join all rooms at that point.

I can see that you can emit to multiple rooms like this:

io.to('room1').to('room2').to('room3').emit('some event');

Is there a way to join multiple rooms at the same time in socket?

socket.join('room1').join('room2').join('room3')? or socket.join('room1', 'room2', 'room3')

Or am I best off doing something like:

rooms = ['room1', 'room2', 'room3'];

rooms.forEach(room => {
   socket.join(room)
});

I have an application where a user can get a list of chat rooms they are in, they can then click into any specific chat room they want. Currently the socket joins the room when the user clicks into a specific room and the socket leaves the room when the user goes back to the main list of chat rooms. This means that when the user is on the chat list page their socket is not in any rooms (bar the default room that the connection event makes) and thus new messages are not pushed to them in real time when on this page.

I plan that when the user loads the chat list page, they join all rooms at that point.

I can see that you can emit to multiple rooms like this:

io.to('room1').to('room2').to('room3').emit('some event');

Is there a way to join multiple rooms at the same time in socket?

socket.join('room1').join('room2').join('room3')? or socket.join('room1', 'room2', 'room3')

Or am I best off doing something like:

rooms = ['room1', 'room2', 'room3'];

rooms.forEach(room => {
   socket.join(room)
});
Share Improve this question asked Jul 8, 2020 at 12:53 ConorConor 1231 gold badge1 silver badge5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 15

Yes, just put the array into the join function:

rooms = ['room1', 'room2', 'room3'];
socket.join(rooms);

Docs: https://socket.io/docs/server-api/#socket-join-rooms-callback

发布评论

评论列表(0)

  1. 暂无评论