What is the proper way to manage multiple chat rooms with socket.io?

前端 未结 2 900
温柔的废话
温柔的废话 2021-01-31 05:48

What is the proper way to manage multiple chat rooms with socket.io?

So on the server there would be something like:

io.sockets.on(\'connection\', functi         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 06:34

    Socket.IO v0.7 now gives you one Socket per namespace you define:

    var room1 = io.connect('/room1');
    room1.on('message', function () {
        // chat socket messages
    });
    room1.on('disconnect', function () {
        // chat disconnect event
    });
    
    var room2 = io.connect('/room2');
    room2.on('message', function () {
        // chat socket messages
    });
    room2.on('disconnect', function () {
        // chat disconnect event
    });
    

    With different sockets, you can selectively send to the specific namespace you would like.

    Socket.IO v0.7 also has concept of "room"

    io.sockets.on('connection', function (socket) {
      socket.join('a room');
      socket.broadcast.to('a room').send('im here');
      io.sockets.in('some other room').emit('hi');
    });
    

    Source: http://socket.io/#announcement

提交回复
热议问题