Forward all messages to socket.io room

624 Views Asked by At

If the client emits a message to a room, how can I get that message sent to all other clients in the room?

Currently on the server I have to do:

    io.on('connection', function (socket) {
        socket.on('join', function (room) {
            socket.join(room);
            socket.on('food.create', function (foods) {
                socket.broadcast.to(room).emit('food.create', foods);
            });
            socket.on('food.update', function (foods) {
                socket.broadcast.to(room).emit('food.update', foods);
            });
            socket.on('food.remove', function (foods) {
                socket.broadcast.to(room).emit('food.remove', foods);
            });
        });
    });
    io.listen(3000);

Which is fine now there's only 3 messages, but when I add more it's going to get long. Does socket.io provide a way of automatically forward all messages form one client to all the other clients in that room?

1

There are 1 best solutions below

0
On

This is the example off the socket.io docs page that shows how to use events and key:value sets for data:

var io = require('socket.io')();
io.on('connection', function(socket){
socket.emit('an event', { some: 'data' });
});

Why not use this construct to pass the messages around? Put your data in the data object along with what you want the respective client to do with that data as a key:value set. Something like this:

io.to('your_room').emit('food', { todo: 'delete', name: 'macaroni' });
});

The server can then simply broadcast that event to all other clients in the room. That way you don't have to filter messages on the server at all.

The other clients then receive the message and do whatever you want based on the data.todo and data.name values.