Skip to content

Why is the client not receiving the socket.io broadcast (rooms)?

My client is not receiving the broadcast sent to the room. If I replace socket.to(roomName).emit('join', currentUser); with socket.emit('join', currentUser); the client receives the broadcast, but I’d like to use rooms here. Any help would be greatly appreciated.

app.js

// Game
app.get('/game', (req, res) => {
    const cookies = req.cookies;
    const currentUser = cookies['current_user'];
    const roomName = cookies['room_name'];

    if (roomName) {
        res.render('pages/game', {
            room: roomName
        });

        io.of('/game').on('connection', socket => {
            console.log('a user connected');
            socket.on('disconnect', () => {
                console.log('user disconnected');
            });

            socket.join(roomName);

            socket.to(roomName).emit('join', currentUser);
        });
    } else {
        res.redirect('/login');
    }
});

game.ejs

const socket = io("/game");

socket.on('join', function(user) {
    console.log(`${user} joined`);
});

Also, could I replace this:

if (roomName) {
    // stuff
} else {
    // other stuff
}

with this:

if (!roomName) {
    // other stuff
    return;
}
// stuff

Answer

According to the documentation, if you use socket.to('room').emit(...) instead of io.in('room').emit(...), it will be broadcasted to all sockets in the room except the sender. That’s where your problem lies.

The reason socket.emit(...) works is because you’re sending it directly and only to the sender.

This emit cheatsheet is quite useful to figure out which combinations of io/socket and to etc affect where messages get sent to.