Socket.IO subscribe to multiple channels

前端 未结 1 993
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 10:31

I want to build a simple chat room system on top of Socket.IO where user can create a new chat room and then people can start chatting.

This sound simple but as the

相关标签:
1条回答
  • 2020-12-12 11:26

    This is all pretty straightforward with the socket.io rooms feature. Take a look at the documentation on LearnBoost wiki.

    https://github.com/LearnBoost/socket.io/wiki/Rooms

    It allows for being connected to multiple rooms over a single socket. I put together a quick test with the following code.

    Server

    io.sockets.on('connection', function(client){
        client.on('subscribe', function(room) { 
            console.log('joining room', room);
            client.join(room); 
        })
        
        client.on('unsubscribe', function(room) {  
            console.log('leaving room', room);
            client.leave(room); 
        })
    
        client.on('send', function(data) {
            console.log('sending message');
            io.sockets.in(data.room).emit('message', data);
        });
    });
    

    Client

     var socket = io.connect();
     socket.on('message', function (data) {
      console.log(data);
     });
     
     socket.emit('subscribe', 'roomOne');
     socket.emit('subscribe', 'roomTwo');
     
     $('#send').click(function() {
      var room = $('#room').val(),
       message = $('#message').val();
       
      socket.emit('send', { room: room, message: message });
     });
    

    Sending a message from an Express route is pretty simple as well.

    app.post('/send/:room/', function(req, res) {
        var room = req.params.room
            message = req.body;
    
        io.sockets.in(room).emit('message', { room: room, message: message });
    
        res.end('message sent');
    });
    
    0 讨论(0)
提交回复
热议问题