socket.io join/leave

前端 未结 2 1670
长发绾君心
长发绾君心 2021-02-05 06:54

I\'m on the socket.io wiki looking into using rooms but join and leave are not working, i\'m wondering if they may have changed up a few things but not had the chance to update

相关标签:
2条回答
  • 2021-02-05 07:25

    You're probably not declaring 'socket' correctly either that of you haven't installed Socket-io correctly. Try the following...

    var io = require("socket.io");
    
    var socket = io.listen(80);
    
    socket.join('room');
    
    socket.leave('room');
    

    There's a useful executable example here.

    0 讨论(0)
  • 2021-02-05 07:36

    It looks like you had the socket.join on the client side. Its a server side function.

    Put this on the server:

    io.sockets.on('connection', function (socket) {
    
        socket.on('subscribe', function(data) { socket.join(data.room); })
    
        socket.on('unsubscribe', function(data) { socket.leave(data.room); })
    
    });
    
    setInterval(function(){
        io.sockets.in('global').emit('roomChanged', { chicken: 'tasty' });
    }, 1000);
    

    And this on the client:

    var socket = io.connect();
    
    socket.emit("subscribe", { room: "global" });
    
    socket.on("roomChanged", function(data) {
        console.log("roomChanged", data);
    });
    
    0 讨论(0)
提交回复
热议问题