Consider this Express server using Socket.IO:
io.to('room42').emit('message', 'hello');What is the behavior when no clients have joined room42?
Think about how Socket.IO handles empty rooms when emitting.
Socket.IO silently ignores emits to empty rooms. No error is thrown and no clients receive the message.
Given a socket connection, which code sends a message to all clients in room1 except the sender?
Remember that broadcast excludes the sender.
socket.broadcast.to('room1').emit(...) and socket.to('room1').emit(...) send to all clients in room1 except the sender. io.to('room1') sends to all clients in the room, including the sender if it is in the room.
Look at this code snippet:
socket.on('join', (room) => {
socket.join(room);
});
socket.on('send', (room, msg) => {
io.to(room).emit('message', msg);
});Clients report they never receive the 'message' event. What is the most likely cause?
Consider the asynchronous nature of socket.join.
socket.join(room) returns a promise. If the server emits immediately after calling join without waiting, the socket may not be in the room yet, so clients don't receive the message.
Assume 3 clients: A, B, and C.
Client A and B join roomX. Client C joins roomY.
Server runs:
io.to('roomX').emit('notify', 'hello');How many clients receive the 'notify' event?
Count clients in roomX.
Only clients A and B are in roomX, so both receive the message. Client C is in a different room.
io.in(room).emit() vs io.to(room).emit()?In Socket.IO, what is the difference between io.in(room).emit('event') and io.to(room).emit('event')?
Check the official Socket.IO documentation for in and to.
io.in(room) and io.to(room) are aliases and behave the same way, sending to all clients in the specified room.