node.js - Continually trying to reconnect until a connection is established -
i'm trying create routine following
while(true) { cxn = connect(addr); if(!cxn) { sleep(1000); continue; } else { break; } }
however, due asynchronous nature of nodejs , websocket library using (ws), appears forced use callbacks detecting successful connection vs error. can't figure out how adapt algorithm above because event of successful connection vs failed assumed occur within loop , not bound asynchronous function.
here example of mean illustrate point trying make:
while(true) { cxn = connect(addr); cxn.on('error', function(error) { sleep(1000); continue; // invalid }); cxn.on('connect', function() { break; // invalid }); }
as can see here. both continue , break statements invalid because occur within bounds of callback function isn't called inside bounds of loop.
how go implementing desired functionality given asynchronous design of node , ws?
**edit: ** have tried modify code make block until connection established. however, still unable connection , program hangs. assume while loop somehow blocking execution of event loop. ideas?
code:
var websocket = require('ws'); var socket = null; function try_connection(addr) { var connection_status = 'connecting'; console.log("attempting connect web socket server..."); socket = new websocket(addr); socket.on('error', function(error) { if(error.errno == 'econnrefused') { console.log('connrefused'); debugger; } else { console.log('unrecoverable error...'); process.exit(-1); } }); socket.on('open', function() { console.log('connection opened'); debugger; connection_status = 'connected'; }); while(connection_status != 'connected') { settimeout(100); continue; } return socket; } try_connection('ws://127.0.0.1:1337'); console.log('hello world');
this can done asynchronous "recursive" function:
function tryconnecting(callback) { var cxn = connect(addr); cxn.on('error', function(error) { settimeout(tryconnecting.bind(this, callback), 1000); }); cxn.on('connect', function() { callback(cxn); }); }
tryconnecting
calls repeatedly, in one-second intervals (using settimeout
), until connect()
call causes connect
event fire. when does, instead of queuing settimeout
call run tryconnecting
, callback
function runs cxn
argument.
anything want after connection completes should go inside of callback
function pass tryconnecting
.
Comments
Post a Comment