最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Socket.io event listening on a specific room - Stack Overflow

programmeradmin5浏览0评论

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

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');
Share Improve this question asked Aug 8, 2014 at 2:23 lsharirlsharir 1211 gold badge1 silver badge5 bronze badges 1
  • Did you get the solution? – Ashish Patel Commented Sep 19, 2020 at 14:09
Add a ment  | 

2 Answers 2

Reset to default 8

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 "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.

发布评论

评论列表(0)

  1. 暂无评论