From 11546b298aed051c96a77fbda01d18c12e34ed67 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Fri, 30 Sep 2016 01:46:00 -0400 Subject: [PATCH] handle sigint --- wsclient.js | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/wsclient.js b/wsclient.js index 4e7c529..0ae52d0 100644 --- a/wsclient.js +++ b/wsclient.js @@ -40,13 +40,15 @@ return; //*/ var tunnelUrl = 'wss://pokemap.hellabit.com:3000/?access_token=' + token; + var wstunneler; function run() { - var wstunneler = new WebSocket(tunnelUrl, { rejectUnauthorized: false }); + var retry = true; + var localclients = {}; + wstunneler = new WebSocket(tunnelUrl, { rejectUnauthorized: false }); function onOpen() { console.log('[open] tunneler connected'); - var localclients = {}; /* setInterval(function () { @@ -163,16 +165,43 @@ return; wstunneler.on('open', onOpen); wstunneler.on('close', function () { - console.log('retry on close'); - setTimeout(run, 5000); + console.log('closing tunnel...'); + process.removeListener('exit', onExit); + Object.keys(localclients).forEach(function (cid) { + try { + localclients[cid].end(); + } catch(e) { + // ignore + } + + delete localclients[cid]; + }); + + if (retry) { + console.log('retry on close'); + setTimeout(run, 5000); + } }); wstunneler.on('error', function (err) { console.error("[error] will retry on 'close'"); console.error(err); }); + + function onExit() { + retry = false; + console.log('on exit...'); + try { + wstunneler.close(); + } catch(e) { + console.error(e); + // ignore + } + } + + process.on('exit', onExit); + process.on('SIGINT', onExit); } run(); - }());