简体   繁体   中英

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');

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM