在客户端按下按钮后,将调用socket.emit
,其参数由输入框定义。这是服务器端socket.on
:
socket.on('createRoom', function(roomName) {
socket.join('Room 1');
console.log(io.sockets.adapter);
console.log(io.sockets.adapter.rooms);
let clients = io.sockets.adapter.rooms['Room 1'].sockets;
console.log('A user joined the room with the name: ' + roomName + ". The user's name is " + raceResponse.user_name);
console.log(clients);
socket.emit('roomCreated', clients);
});
此后,我将其更改为在服务器端定义房间名称,因为出现错误:
let clients = io.sockets.adapter.rooms['Room 1'].sockets;
TypeError: Cannot read property 'sockets' of undefined
但是请注意上面的行:它们分别记录io.sockets.adapter
和io.sockets.adapter.rooms
。我相信后者是所有房间的清单,因为它给了我:
{ ZJ81Hw0FkCIQxg86AAAA: [], UoE9k4lTnGMUB9y6AAAB: [], 'Y-Tr2j9MxCzZokSSAAAC': [ 'Y-Tr2j9MxCzZokSSAAAC': true ] }
在我看来,对象中的第一项是默认房间,另一项是刚创建的房间,其中有一个用户。让我感到困惑的是,该房间没有被调用“ Room 1”,这正是我所期望的。
我可能完全误解了io.sockets.adapter.rooms
的含义,因此,请告诉我。
io.sockets.adapter
给我:
Adapter {
nsp: Namespace {
name: '/',
server: Server {
nsps: [Object],
_path: '/socket.io',
_serveClient: true,
_adapter: [Function: Adapter],
_origins: '*:*',
sockets: [Circular],
eio: [Server],
httpServer: [Server],
engine: [Server]
},
sockets: [ [Socket] ],
connected: { wKTl5kLVfhWSTSt0AAAB: [Socket] },
fns: [],
ids: 0,
acks: {},
adapter: [Circular]
},
rooms: {
'-zzOKEUrvDOj_345AAAA': [],
wKTl5kLVfhWSTSt0AAAB: [ wKTl5kLVfhWSTSt0AAAB: true ]
},
sids: { wKTl5kLVfhWSTSt0AAAB: { wKTl5kLVfhWSTSt0AAAB: true } },
encoder: Encoder {}
}
{
'-zzOKEUrvDOj_345AAAA': [],
wKTl5kLVfhWSTSt0AAAB: [ wKTl5kLVfhWSTSt0AAAB: true ]
}
有人可以提供任何解释或替代方法吗?非常感谢。
答案 0 :(得分:1)
不知道您的Socket-io版本,但是服务器的设置如下:
<div>Hello world</div>
客户端设置如下:
let io = require('socket.io');
io.on('connection', function(socket){
socket.join('Test');
socket.join('Test1');
console.log(io.sockets.adapter.rooms);
});
我从Nodejs v8.9.3 / Socket.io v2.2.0上的服务器获得的结果:
let io = require('socket.io-client');
socket = io.connect("http://localhost:8090")
在Socket.IO documentation I found a reference to a method上浏览以显示一个插座所在的所有房间,并对其进行了测试:
{
c9kG4WD5hFlLUOZrAAAA: Room { sockets: { c9kG4WD5hFlLUOZrAAAA: true }, length: 1 },
Test: Room { sockets: { c9kG4WD5hFlLUOZrAAAA: true }, length: 1 },
Test2: Room { sockets: { c9kG4WD5hFlLUOZrAAAA: true }, length: 1 }
}
哪个返回:
let rooms = Object.keys(io.sockets.adapter.rooms);
console.log(rooms);
仅按名称列出所有当前存在的房间。
我通过以下方式对此进行了改进:
[ 'c9kG4WD5hFlLUOZrAAAA', 'Test', 'Test2' ]
哪个返回:
let roomName = rooms[rooms.length-1]; //Get last room pushed
console.log('A user joined the room with the name: ' + roomName + ". The user's name is X");
您可以自己以阵列的形式跟踪房间的名称,但是您要格外小心,因为这可能会导致潜在的内存泄漏。
但是,如果您想要的只是最后一个加入的房间,则可以使用任何值作为var并将其传递给emit。