Reputation: 823
I am attempting to use the net lib in Node.js to do simple message passing. In the example on Nodejs.org they provide the following code as a basic echo server:
var net = require('net');
var server = net.createServer(function(c) { //'connection' listener
console.log('server connected');
c.on('end', function() {
console.log('server disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
console.log('server bound');
});
and a client for said server:
var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('client connected');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
The example above works, however, if you remove the client.end();
from the client code and force close the script on the client end (simulating a client crashing) the server crashes as well with the error:
Error: read ECONNRESET
at errnoException (net.js:904:11)
at TCP.onread (net.js:558:19)
I attempted to catch the error in the server code with c.on("error",function(){})
as well as server.on('error', function (e) {});
but in both cases the server still crashes when the client disconnects without using client.end()
What is the propper way of checking for this error so that the server does a console.log('connection reset by peer')
instead of crashing?
UPDATE: I tried this same code on my linux box and it seems to work just fine ... so why does it work in linux but not in windows?
Upvotes: 2
Views: 4062
Reputation: 2924
you can catch that error by adding this code inside yours 'createServer' function:
process.on('uncaughtException', function (err) {
console.error(err.stack);
console.log("Node NOT Exiting...");
});
Upvotes: 2