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
1 Answer
Reset to default 15Yes, 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