我有一个 node.js 聊天服务器的以下代码。服务器运行,客户端可以远程登录和连接。但是当客户端发送消息时,它会自动断开所有其他客户端的连接,我不明白我做错了什么。
var net = require('net');
var chatServer = net.createServer();
var clientList = [];
chatServer.on('connection', function(client) {
client.name = client.remoteAddress + ':' + client.remotePort;
client.write("Hi " + client.name + "!\n");
clientList.push(client);
client.on('data', function(data) {
broadcast(data, client);
});
client.on('end', function() {
clientList.splice(clientList.indexOf(client), 1);
});
client.on('error', function(e) {
console.log(e);
});
});
function broadcast(message, client) {
var cleanup = [];
for(var i = 0; i < clientList.length; i++) {
if(client !== clientList[i]) {
if(clientList[i].writeable) {
clientList[i].write(client.name + " says " + message);
} else {
cleanup.push(clientList[i]);
clientList[i].destroy();
}
}
}
for(i = 0; i < cleanup.length; i++) {
clientList.splice(clientList.indexOf(cleanup[i]), 1);
}
}
chatServer.listen(9000);