-
-
Save redanium/d1c059fbc6c7b2bb55c8ce37f4c1a90b to your computer and use it in GitHub Desktop.
Node.js Re-connecting Socket
This file contains 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 characters
// | |
// 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(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment