为什么 Nodejs 的 net.connect() 会遇到 read ECONNRESET 错误,然而 telnet 连接却没有问题
为什么 Nodejs 的 net.connect() 会遇到 read ECONNRESET 错误,然而 telnet 连接却没有问题
如题
var client = net.connect(43, server, function() {
client.write(domain + '\n', 'ascii')
})
yields
{ Error: read ECONNRESET
at exports._errnoException (util.js:1050:11)
at TCP.onread (net.js:581:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
However,
telnet xxxx 43
yields
telnet xxx 43
Trying xxx...
Connected to xxx.
Escape character is '^]'.
5 回复
telnet 没写东西呀。为了一致,把 client.write() 删掉试试?
telnet 是有写东西的 没放出来
😂 找到问题了 要’\r\n’不是’\n’
遇到 Node.js 的 net.connect()
抛出 read ECONNRESET
错误,而 telnet
连接却正常的情况,通常意味着在 Node.js 客户端与服务器之间的连接在某个阶段被对方(通常是服务器)强制关闭了。以下是一些可能的原因和排查方法:
-
服务器超时: 服务器可能配置了连接超时,如果客户端在一定时间内没有发送数据或没有正确保持连接,服务器可能会关闭连接。
-
协议不匹配: 如果 Node.js 客户端与服务器在协议级别不匹配(例如,发送的数据格式或顺序不正确),服务器可能会认为连接异常并断开。
-
网络问题: 尽管
telnet
可以成功连接,但可能存在中间网络设备(如防火墙、负载均衡器)干扰 Node.js 客户端的连接。 -
客户端代码问题: Node.js 客户端可能在处理连接时存在逻辑错误,导致连接被意外关闭。
下面是一个简单的 Node.js 客户端示例,展示了如何捕获 ECONNRESET
错误:
const net = require('net');
const client = net.createConnection({ port: 8080 }, () => {
console.log('Connected to server');
client.write('Hello, server!');
});
client.on('error', (err) => {
if (err.code === 'ECONNRESET') {
console.error('Connection was reset by peer');
} else {
console.error(`Error: ${err.message}`);
}
});
client.on('end', () => {
console.log('Disconnected from server');
});
建议检查服务器日志,确认是否有关于连接关闭的详细错误信息,同时确保客户端和服务器之间的协议和数据格式完全一致。