简体   繁体   English

在Socket.io中创建房间

[英]Creating Rooms in Socket.io

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: 我在socket.io的客户端遇到困难,我想在客户端调用此代码在socket.io中创建一个房间:

var rooms = [];
socket.on('create', function (roomname) {
    rooms[room] = room;
    socket.room = roomname;
            socket.join(roomname);
    subscribe.subscribe(socket.room);
});

I don't know if this is correct, if not please help me to correct this guys. 我不知道这是否正确,如果没有请帮助我纠正这些家伙。 I'm not that to pro in node js and sockets but i've already read their wikis. 我不是那个在节点js和套接字中专业但我已经读过他们的wiki了。 Is there any possible way to create room? 有没有办法创造空间?

Rooms in Socket.IO don't need to be created, one is created when a socket joins it. 不需要创建Socket.IO中的房间,当套接字加入时会创建一个房间。 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 . 在上面的示例中,创建了一个房间,其名称在变量room指定。 You don't need to store this room object anywhere, because it's already part of the io object. 您不需要将此房间对象存储在任何位置,因为它已经是io对象的一部分。 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);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM