net-reconnect
Provides a tcp connection that reconnects dropped connections.
Quick Start
To install run the following from the root of your project.
$ npm install --save net-reconnect
Usage
Short version.
DurableConnection = require('net-reconnect');
var dcon = new DurableConnection(9092, 'localhost');
var socket = dcon.connect();
dcon.on('connect', function() {
socket.write('hello world!');
});
Longer version.
Our default behavior is to reconnect after one second, then two
seconds, then four . . . up to maxReconnectMillis
.
The default logging method is console.log
. You can change it to any function you
like. If you no like logging, make it a no-op function.
DurableConnection = require('net-reconnect');
// DurableConnection takes the same arguments as net.connect.
// http://nodejs.org/api/net.html
var dcon = new DurableConnection(9092, 'localhost');
// Optionally change some defaults
dcon.reconnectMillis = 7000; // default: 1000
dcon.maxReconnectMillis = 60000; // default: Number.MAX_SAFE_INTEGER
// we don't need no stinking logging
dcon.log = function() {}; // default: console.log
// connect takes no arguments.
var socket = dcon.connect();
// DurableConnection emits the same events as Socket.
// Register event callbacks on dcon (not socket). Otherwise
// the callbacks will be lost on reconnect.
// Hmm, maybe I could make it work either way if I copied them.
dcon.on('connect', function() {
console.log('show time!');
// you now have a socket connection that will never die.
// well, it may die, but it will keep trying to reconnect forever.
// if you want to change socket options, do it here in connect
// otherwise they will be lost on reconnect.
// Hmm, maybe I could make it work either way if I copied them.
socket.setKeepAlive(true);
});
dcon.on('error', function(err) {
// make sure to register an error handler.
console.log('ugh!', err);
});