在 Socket.io 中创建房间 [英] Creating Rooms in Socket.io

查看:122
本文介绍了在 Socket.io 中创建房间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想请求您的帮助.我在 socket.io 的客户端遇到了困难,我想在我的客户端调用这段代码在 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:

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

我不知道这是否正确,如果不正确,请帮助我纠正这些人.我不是节点 js 和套接字的专业人士,但我已经阅读了他们的 wiki.有没有办法创造空间?

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?

推荐答案

Socket.IO 中的 Room 不需要创建,一个 socket 加入时创建.它们在服务器端加入,因此您必须使用客户端指示服务器.

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

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

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

这篇关于在 Socket.io 中创建房间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆