Node.js App Crashes Whenever The Remote Host Closes Socket Connection

- 1 answer

Here is the source code of the server socket :

const server = net.createServer(client => {
   // 'connection' listener.
   let processing = false;

   client.on('data', data => {
      const batches = data.toString().split(',');

      if (!processing && batches && batches.length) {
         processing = true;

         processBatch(batches, error => {
            const status = error ? 'ERR' : 'SUCC';

            logger.verbose('... Ended with status : ' + status);

            client.write(status, () => client.end());
   client.on('timeout', () => {
     logger.warn('Client socket did time out');

   //client.on('end', () => {});
server.on('error', error => {'Socket error');
   logger.error('Error: ', error);
server.listen(config.socket.port, () => {
   console.log('*** Socket listening on port', config.socket.port);

The client would connect, send it's data, and then remotely close the connection, which makes the server error handler be fired with, logging the message :

Error: This socket has been ended by the other party
    at Socket.writeAfterFIN [as write] (net.js:441:14)
    at file:///home/thermo/bwkl/src/service.js:191:20
    at file:///home/thermo/bwkl/src/service.js:123:13 {
 code: 'EPIPE'

How can this be prevented, and gracefully close the client socket when the remote host prematurely ended the connection?



The server error handler does not catch the connection error because the error event is emitted by the client.

You should define a listener for error event on the client instance in order to handle the error in question:

client.on('error', (err) => {
  console.log('Connection error:', err.message);

This will prevent the Node.js process from crash. You can handle the error as desired inside the listener.