lsharir
lsharir

Reputation: 121

Socket.io event listening on a specific room

I'm not sure it is possible, but I really need that feature. Can I do something like:

client side

sio = io.connect(url);
sio.to('room1').on('update', function(roomName) {
    console.log(roomName);
});

Which will be triggered whenever an update event is emitted to 'room1'?

server side:

sockets.to('room1').emit('update', 'room1');

Upvotes: 8

Views: 16349

Answers (2)

David Rinnan
David Rinnan

Reputation: 325

The "easy" way is to make sure that your emits from the server include the room in the payload.

sockets.to(room).emit('update', {room: room, message: 'hello world!'})

Most probably you want to do the same on the client-side of things. So that the messages sent from the client to the server includes a room identifier so that the message can be routed correctly.

Or you implement name spaces.

Upvotes: 4

Ferdi265
Ferdi265

Reputation: 2969

That, unfortunately, doesn't work just on the client side. But you can do it on the server side.

Server Setup:

sockets.on('connection', function (socket) {
    socket.on('join', function (room) {
        socket.join(room);
    });
});

//...

sockets.to('room1').emit('update', 'room1');

Client:

sio.emit('join', 'room1');
sio.on('update', function (room) {
    console.log(room);
});

Upvotes: 8

Related Questions