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

查看:327
本文介绍了在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中的房间,当套接字加入时会创建一个房间。它们在服务器端加入,因此您必须使用客户端指示服务器。

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

在上面的例子中,创建了一个房间,其名称在变量中指定室。您无需将此房间对象存储在任何位置,因为它已经是 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天全站免登陆