Skip to content

Instantly share code, notes, and snippets.

@sio2boss
Created August 25, 2013 14:19

Revisions

  1. sio2boss created this gist Aug 25, 2013.
    65 changes: 65 additions & 0 deletions client-socket-reconnect.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    //
    // Simple example of using net.Socket but here we capture the
    // right events and attempt to re-establish the connection when
    // is is closed either because of an error establishing a
    // connection or when the server closes the connection.
    //

    // Requires
    var net = require('net');

    // Create socket
    var port = 55555;
    var host = 'localhost';
    var timeout = 1000;
    var retrying = false;

    // Functions to handle socket events
    function makeConnection () {
    socket.connect(port, host);
    }
    function connectEventHandler() {
    console.log('connected');
    retrying = false;
    }
    function dataEventHandler() {
    console.log('data');
    }
    function endEventHandler() {
    // console.log('end');
    }
    function timeoutEventHandler() {
    // console.log('timeout');
    }
    function drainEventHandler() {
    // console.log('drain');
    }
    function errorEventHandler() {
    // console.log('error');
    }
    function closeEventHandler () {
    // console.log('close');
    if (!retrying) {
    retrying = true;
    console.log('Reconnecting...');
    }
    setTimeout(makeConnection, timeout);
    }

    // Create socket and bind callbacks
    var socket = new net.Socket();
    socket.on('connect', connectEventHandler);
    socket.on('data', dataEventHandler);
    socket.on('end', endEventHandler);
    socket.on('timeout', timeoutEventHandler);
    socket.on('drain', drainEventHandler);
    socket.on('error', errorEventHandler);
    socket.on('close', closeEventHandler);

    // Connect
    console.log('Connecting to ' + host + ':' + port + '...');
    makeConnection();