将连接用户发送到客户端会导致范围错误

Sending connect users to client causes Range Error

本文关键字:范围 错误 客户端 连接 用户      更新时间:2023-09-26

我正在尝试发送一个连接到服务器的用户数组,并将它们发送到客户端,在那里我将循环使用它们。

app.js

io.on('connection', function (socket) { 
    socket.on('users', function (data) {
        var clients = io.sockets.sockets;
        socket.emit('clients', { user : clients });
    });
});

index.html

socket.emit('users', { });
socket.on('clients', function(data) {
    console.log(data);
    //for(var obj in data) {
    //  console.log(data[obj]);
    //}
});

我遇到的问题是,当试图将用户传递给客户端时,它会引发RangeError。

有两个问题-

  1. 我这样做对吗?我是node.js和网络/服务器编码的新手

  2. 为什么我会得到RangeError。

由于在注释中显示了这是一个堆栈溢出错误,因此看起来io.sockets.sockets指向的对象在某个地方有一个循环引用。

我在这里根据你在问题中所说的进行假设,但由于你试图简单地发送连接用户的列表,也许你可以在将其发送给客户端之前合成clients列表:

io.on('connection', function (socket) { 
    socket.on('users', function (data) {
        var clients = io.sockets.sockets.map(function (client) {
          // Derive some value---anything---from the `client` value. Once
          // done that, return the resulting client value. Below, you can
          // see that I have derived nothing, but I recommend that you *do*
          // derive *something*.
          return client;
        });
        socket.emit('clients', { user : clients });
    });
});