Skip to content

Instantly share code, notes, and snippets.

@branneman
Created November 8, 2014 14:51
Show Gist options
  • Save branneman/0a77af5d10b93084e4f2 to your computer and use it in GitHub Desktop.
Save branneman/0a77af5d10b93084e4f2 to your computer and use it in GitHub Desktop.
Node.js TCP Socket - if either of them breaks, they'll keep trying to reconnect
var net = require('net');
//
// Client
//
function openSocket() {
var socket = net.connect(3e3);
socket.setKeepAlive(true);
socket.on('connect', onConnect.bind({}, socket));
socket.on('error', onError.bind({}, socket));
}
var interval;
function onConnect(socket) {
console.log('Socket is open!');
interval = setInterval(function() {
var msg = parseInt(+new Date) + '';
socket.write(msg, function() {
console.log('Sent:', msg);
});
}, 500);
}
function onError(socket) {
console.log('Socket error!');
// Kill socket
clearInterval(interval);
socket.destroy();
socket.unref();
// Re-open socket
setTimeout(openSocket, 1e3);
}
openSocket();
var net = require('net');
//
// Server
//
var server = new net.Server();
server.on('connection', function(socket) {
console.log('Socket is open!');
socket.setEncoding('utf8');
socket.on('data', function(data) {
console.log('Received:', data);
});
socket.on('error', function() {
console.log('Socket error!');
});
});
server.listen(3e3, function() {
console.log('Server is listening!');
});
@ningji2
Copy link

ningji2 commented Jul 30, 2015

Excellent example, thanks very much !

@AlexFrazer
Copy link

This is helpful, thank you good sir

@ayushpratap
Copy link

How to determine that a client has disconnected / not connected to the server any more ?
And we are trying to write to the socket ?
How to determine this without waiting for timeout of the socket ?

@KXDev
Copy link

KXDev commented Mar 6, 2019

How to determine that a client has disconnected / not connected to the server any more ?
And we are trying to write to the socket ?
How to determine this without waiting for timeout of the socket ?

If client closed connection correctly (by end() ), socket.close() will be fired immediately.
Otherwise you need to write your own ACK system for each message, and to not send new portion of data while you not received ACK.

@mAPBhlJ
Copy link

mAPBhlJ commented Sep 4, 2019

This doesn't work for me.

Pulling the network cable out and back in causes: "ECONNRESET".
And causes [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed (for each time you try to write).

And then for each time you try to write; starts a new connection; but for some reason doesn't continue gracefully.
Also; it doesn't even print the actual error.

@chipbrommer
Copy link

Printing the error is a simple fix. in the 'error' listener; change the console log to 'console.log(error);' this will output the error instead of the verbiage he has written.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment