Dynamic Namespaces Socket.IO

后端 未结 5 583
再見小時候
再見小時候 2021-01-30 09:32

How can I use dynamic namespaces in socket.io.

I\'m looking in the (poor) documentation, and it says that namespaces must be used like this:

io.of(\'/news\

5条回答
  •  囚心锁ツ
    2021-01-30 09:55

    I would use "rooms" to support your dynamic content.

    Server Side

    var server = require('http').createServer(),
        io     = require('socket.io')(server);
    
    
    io.on('connection', function(socket){
    
      var room = socket.handshake['query']['r_var'];
    
      socket.join(room);
      console.log('user joined room #'+room);
    
      socket.on('disconnect', function() {
        socket.leave(room)
        console.log('user disconnected');
      });
    
      socket.on('chat message', function(msg){
        io.to(room).emit('chat message', msg);
      });
    
    });
    
    server.listen(3000);
    

    Client Side

    var socket_connect = function (room) {
        return io('localhost:3000', {
            query: 'r_var='+room
        });
    }
    
    var random_room = Math.floor((Math.random() * 2) + 1);
    var socket      = socket_connect(random_room);
    
    socket.emit('chat message', 'hello room #'+random_room);
    ....
    

提交回复
热议问题