node.js 在 Socket.io 中创建房间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19150220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:51:29  来源:igfitidea点击:

Creating Rooms in Socket.io

javascriptnode.jssocketssocket.io

提问by Joenel de Asis

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. Is there any possible way to create room?

我不知道这是否正确,如果不正确,请帮助我纠正这些人。我不是 node js 和 sockets 的专家,但我已经阅读了他们的 wiki。有没有办法创造空间?

回答by hexacyanide

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.IO 中的房间不需要创建,当一个套接字加入它时就会创建一个。它们在服务器端加入,因此您必须使用客户端指示服务器。

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 ioobject. You can then treat the room like its own socket instance.

在上面的示例中,创建了一个房间,其名称在变量 中指定room。您不需要将此房间对象存储在任何地方,因为它已经是io对象的一部分。然后,您可以将房间视为其自己的套接字实例。

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);
  });
});