gpt4 book ai didi

node.js - Node : This socket is closed

转载 作者:搜寻专家 更新时间:2023-10-31 22:40:01 28 4
gpt4 key购买 nike

我在 Node.js 中使用 tcp 套接字与 Java 客户端通信。

请参阅下面我非常基本的服务器实现:

var server = my_http.createServer();
echo.installHandlers(server, {
prefix: '/echo'
});
server.listen(8000, '0.0.0.0');

var socketServer = net.createServer(function (socket) {

// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort

// Put this new client in the list
clients.push(socket);

sockets[socket.name] = socket;

// Handle incoming messages from clients.
socket.on('data', function (data) {

try {
var obj = JSON.parse(data);

if (obj.type == "sendMessage") {
broadcast("{\"id\":\"1\", \"msg\": \"" + obj.msg + "\", \"name\": \"" + obj.name + "\", \"time\": \"" + getDateTime() + "\"}\n", socket);

}
} catch (er) {

}
});

// Remove the client from the list when it leaves
socket.on('end', function () {
try {
clients.splice(clients.indexOf(socket), 1);
} catch (err) {

}
});

// Send a message

function broadcast(message, sender) {
try {
clients.forEach(function (client) {
client.write(message); // ERROR IS HERE
});
} catch (ee) {

}
}

return socket;
}).listen(8080);

出于某种原因,有时我会收到此错误:

events.js:71
抛出参数[1];//未处理的“错误”事件
^
错误:此套接字已关闭。

它发生在这条线上:

client.write(消息);//这里有错误

有什么想法可以防止这种情况发生吗?

最佳答案

或者使用 client.writable 检测套接字是否可用。

    clients.forEach(function (client) {
try {
if (client.writable) {
clientwrite("are u alive");
} else {
console.log('client is not writable');
}
} catch (err) {
console.log("cannot send message.");
}
}

关于node.js - Node : This socket is closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18591989/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com