Created
August 25, 2013 14:19
Revisions
-
sio2boss created this gist
Aug 25, 2013 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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();