NodeJS 发送所有客户端的列表都失败

nodejs send list of all clients fail

本文关键字:列表 失败 客户端 NodeJS      更新时间:2023-09-26

js.目前我已经成功地完成了几项测试

  • 世界您好
  • 服务器-客户端与事件通信
  • 许多房间

但是我不能发送客户端,给客户端,我使用 socket.io

我想这样做的原因是要有一个当前客户的列表

编辑:

我需要在服务器端存储每个用户的信息


我尝试使用

var io = require('socket.io');
var socket = io.listen(9876);
socket.on('connection', function(client) {
client.join('room');
console.log('new client ' + client.toString());
client.in('room').emit('list', client ); //<-- Error here
client.on('message', function(event) {
    console.log('client message! ', event);
    client.send(event);
});
client.on('chat', function(data) {
    client.broadcast.in('room').emit('LDS', data);
    client.in('room').emit('LDS', data);
});
client.on('disconnect', function() {
    console.log('out');
});
});

但抛出此错误

connections property is deprecated. Use getConnections() method
C:'Repos'InWeb'NO'node_modules'socket.io'lib'parser.js:75
  data = JSON.stringify(ev);
              ^
TypeError: Converting circular structure to JSON
at Object.stringify (native)

最初的想法是发送一个客户列表,就像这样

var listClients;
socket.on('connection', function(client) {
client.join('room');
listClients.push(client);
client.in('room').emit('list', listClients); //<-- But throws same error

我猜错误是由客户端上下文给出的

我可以修复它吗?

你发送整个对象客户端,你应该使用这样的东西

Socket.io 连接的用户计数

或者使用名称和 ID 创建数组并发送数组而不是整个节点对象。