Creating Rooms in Socket.io

后端 未结 1 1195
闹比i
闹比i 2020-11-27 11:06

I would like to ask for your help. I\'m having a hard time in my client side of socket.io, I would like to call this code in my client side to create a room in socket.io:

相关标签:
1条回答
  • 2020-11-27 11:49

    Rooms in Socket.IO don't need to be created, one is created when a socket joins it. They are joined on the server side, so you would have to instruct the server using the client.

    socket.on('create', function (room) {
      socket.join(room);
    });
    

    In the example above, a room is created with a name specified in variable room. You don't need to store this room object anywhere, because it's already part of the io object. You can then treat the room like its own socket instance.

    io.sockets.in(room).emit('event', data);
    

    So to create a room from the client, this is what it might look like:

    // client side code
    var socket = io.connect();
    socket.emit('create', 'room1');
    
    // server side code
    io.sockets.on('connection', function(socket) {
      socket.on('create', function(room) {
        socket.join(room);
      });
    });
    
    0 讨论(0)
提交回复
热议问题