Reputation: 53536
Here is the source code of the server socket :
const server = net.createServer(client => {
// 'connection' listener.
let processing = false;
client.setTimeout(config.socket.timeout);
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.end();
});
//client.on('end', () => {});
});
server.on('error', error => {
logger.info('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?
Upvotes: 2
Views: 1400
Reputation: 7665
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.
Upvotes: 3