【发布时间】:2021-01-01 22:23:01
【问题描述】:
如果我尝试 NodeJS 文档中的非常基本的代码
//CLIENT.js
const net = require('net');
const client = net.createConnection({ port: 8124 }, () => {
// 'connect' listener.
console.log('connected to server!');
client.write('I am client');
});
client.on('data', (data) => {
console.log(data)
client.write('I am client');
//client.end(); I don't want to close the connection
});
client.on('end', () => {
console.log('disconnected from server');
});
//SERVER.js
const net = require('net');
const server = net.createServer((c) => {
// 'connection' listener.
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.on('data', (data) => {
console.log(data)
c.write("I am server");
})
c.pipe(c);
});
server.on('error', (err) => {
console.log("Something went worng"); //I hope this will be triggered in cases of error
});
server.listen(8124, () => {
console.log('server bound');
});
现在的问题:-
- 我启动 SERVER.js
node SERVER.js - 然后我在另一个 CMD 选项卡上启动 CLIENT.js
node CLIENT.js。 - 到目前为止一切顺利......'我是服务器我是客户端............'
注意我使用的是 Windows 10
- 现在,我只需按
ctrl + C即可关闭客户端程序,然后服务器端程序终止并抛出“read ECONNRESET”
完整的错误日志
events.js:292
throw er; // Unhandled 'error' event
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:205:27)
Emitted 'error' event on Socket instance at:
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read'
}
我理解为什么理论上会导致这个错误,所以我尝试以不同的方式解决它,因为程序没有触发server.on('error')事件,它只是终止了整个服务器程序。
所以我尝试的是
//SERVER.js
const net = require('net');
const server = net.createServer((c) => {
// 'connection' listener.
console.log('client connected');
try {
c.on('end', () => {
console.log('client disconnected');
});
c.on('data', (data) => {
console.log(data)
c.write("I am server");
})
c.pipe(c);
} catch(e){
//hoping of catching the error
console.log("Here is your error", e)
// !!! But no error is caught here and the program still gets completely terminated
}
});
server.on('error', (err) => {
console.log("Something went worng"); //I hope this will be triggered in cases of error
});
server.listen(8124, () => {
console.log('server bound');
});
那么我应该如何处理“read ECONNRESET”错误呢?
【问题讨论】:
标签: node.js networking error-handling tcp