Node.js 当使用nodejs编写聊天服务器时,如何处理此错误?

Node.js 当使用nodejs编写聊天服务器时,如何处理此错误?,node.js,Node.js,代码如下: var net = require('net'); var clientList = []; var chatServer = net.createServer(function(socket){ socket.write("Hi\n"); clientList.push(socket); socket.setEncoding('utf-8'); socket.on('data', function(data){ for (va

代码如下:

var net = require('net');

var clientList = [];

var chatServer = net.createServer(function(socket){
    socket.write("Hi\n");

    clientList.push(socket);

    socket.setEncoding('utf-8');
    socket.on('data', function(data){
        for (var i = 0; i < clientList.length; i++) {
            clientList[i].write(data);
        };
        socket.end();
    });
}).listen(4000);
但是程序崩溃了: 以下是控制台的输出:

C:\Users\elqstux\Desktop>node wy.js
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: This socket has been ended by the other party
    at Socket.writeAfterFIN [as write] (net.js:289:12)
    at Socket.<anonymous> (C:\Users\elqstux\Desktop\wy.js:13:18)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:529:20)
C:\Users\elqstux\Desktop>node wy.js
events.js:85
投掷者;//未处理的“错误”事件
^
错误:此套接字已被另一方终止
在Socket.writeAfterFIN[as write](net.js:289:12)
在插座上。(C:\Users\elqstux\Desktop\wy.js:13:18)
在Socket.emit(events.js:107:17)
在readableAddChunk(_stream_readable.js:163:16)
在Socket.Readable.push(_stream_Readable.js:126:10)
在TCP.onread(net.js:529:20)

我无法确定出现错误的原因。

当新客户端连接时,您将传入套接字存储在
clientList
数组中,但一旦某些数据到达该套接字,您将使用
socket.end()
关闭它,但不会将其从数组中删除。因此,当您遍历数组并将数据发送到
clientList
数组中的所有套接字时,该列表中的套接字将不再打开,从而产生错误

Socket.writeAfterFIN
错误意味着您试图在关闭套接字后写入它

这就是错误的原因。我不知道你到底想完成什么,所以我不确定应该建议什么样的代码来避免这个错误

此外,您还可以通过添加以下内容自行处理套接字上的错误(这样您的服务器就不会停止):

socket.on('error', function(err) {
    // process error here
});
并且,如果客户端关闭套接字,您还需要处理关闭事件:

socket.on('close', function() {
    // clean up references to this socket as it is no longer open
    // remove it from the `clientList` array and any other references we have to it
});
socket.on('close', function() {
    // clean up references to this socket as it is no longer open
    // remove it from the `clientList` array and any other references we have to it
});