Skip to content

Commit

Permalink
improve ping func
Browse files Browse the repository at this point in the history
  • Loading branch information
jfromaniello committed Mar 8, 2016
1 parent f9e255a commit 8403059
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 28 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"levelup": "~0.18.6",
"lodash": "~2.4.1",
"lru-cache": "~2.6.3",
"ms": "~0.7.1",
"nconf": "https://github.com/jfromaniello/nconf/tarball/master",
"passport": "~0.1.16",
"passport-local": "~0.1.6",
Expand Down
52 changes: 24 additions & 28 deletions ws_validator.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
var WebSocket = require('ws');
var exit = require('./lib/exit');

var jwt = require('jsonwebtoken');
var nconf = require('nconf');
var fs = require('fs');
var Users = require('./lib/users');
var users = new Users();
var async = require('async');
var randomstring = require('randomstring');
var exit = require('./lib/exit');
var jwt = require('jsonwebtoken');
var nconf = require('nconf');
var fs = require('fs');
var Users = require('./lib/users');
var users = new Users();
var async = require('async');
var cb = require('cb');
var ms = require('ms');

var cert = {
key: nconf.get('AUTH_CERT_KEY') || fs.readFileSync(__dirname + '/certs/cert.key'),
Expand Down Expand Up @@ -45,26 +45,22 @@ function ping (client, count, callback) {
callback = function(){};
}

var hash = randomstring.generate(7);

var on_pong = function (data) {
if (data.toString() !== hash) return;
clearTimeout(check);
callback(null, {
failed_pings: count
});
};

var check = setTimeout(function () {
client.removeListener('pong', on_pong);
if (count === 4) {
return callback(new Error('server didnt respond to 4 ping commands'));
var pong = cb(function (err) {
if (err instanceof cb.TimeoutError) {
client.removeListener('pong', pong);
if (count === 4) {
return callback(new Error('server did\'t respond to 4 ping commands'));
}
return ping(client, ++count, callback);
}
console.log('Server didnt respond to ' + (count + 1) + ' ping commands. Re-ping.');
ping(client, ++count, callback);
}, 4000);
callback(null, { failed_pings: count });
}).timeout(ms('4s'));

if (client.readyState !== WebSocket.OPEN) {
return callback(new Error('connection is closed'));
}

client.on('pong', on_pong).ping(hash);
client.once('pong', pong).ping('');
}

var log_from_auth0 = console.log.bind(console, 'auth0'.blue + ':');
Expand Down Expand Up @@ -100,7 +96,7 @@ ws.on('open', function () {
}
done();
});
}, 5000);
}, ms('5s'));
},
function (err) {
console.log(err.message);
Expand Down

0 comments on commit 8403059

Please sign in to comment.