reuse port

This commit is contained in:
AJ ONeal 2018-06-09 20:54:32 +00:00
parent b2a7ecd39b
commit 5ddd85e14e
1 changed files with 24 additions and 13 deletions

View File

@ -4,6 +4,7 @@ var url = require('url');
var PromiseA = require('bluebird'); var PromiseA = require('bluebird');
var jwt = require('jsonwebtoken'); var jwt = require('jsonwebtoken');
var Packer = require('proxy-packer'); var Packer = require('proxy-packer');
var portServers = {};
function timeoutPromise(duration) { function timeoutPromise(duration) {
return new PromiseA(function (resolve) { return new PromiseA(function (resolve) {
@ -258,9 +259,7 @@ module.exports.create = function (state) {
Devices.add(state.deviceLists, domainname, token); Devices.add(state.deviceLists, domainname, token);
}); });
function onDynTcpReady() { function onDynTcpReadyHelper(serviceport) {
var serviceport = this.address().port;
console.info('[DynTcpConn] Port', serviceport, 'now open for', token.deviceId);
//token.dynamicPorts.push(serviceport); //token.dynamicPorts.push(serviceport);
Devices.add(state.deviceLists, serviceport, token); Devices.add(state.deviceLists, serviceport, token);
//var hri = require('human-readable-ids').hri; //var hri = require('human-readable-ids').hri;
@ -300,16 +299,28 @@ module.exports.create = function (state) {
//token.dynamicNames = []; //token.dynamicNames = [];
var onePortForNow = parseInt(token.ports[0], 10) || 0; var onePortForNow = parseInt(token.ports[0], 10) || 0;
// TODO try again with random port if (portServers[onePortForNow]) {
try { //token.ports = [];
token.server = require('net').createServer(onDynTcpConn).listen(onePortForNow, onDynTcpReady); token.server = portServers[onePortForNow];
token.server.on('error', function (e) { token.server.on('connection', onDynTcpConn);
console.error("Server Error assigning a dynamic port to a new connection:", e); onDynTcpReadyHelper(onePortForNow);
}); } else {
} catch(e) { try {
// what a wonderful problem it will be the day that this bug needs to be fixed token.server = require('net').createServer(onDynTcpConn).listen(onePortForNow, function () {
// (i.e. there are enough users to run out of ports) var serviceport = this.address().port;
console.error("Error assigning a dynamic port to a new connection:", e); portServers[serviceport] = this;
console.info('[DynTcpConn] Port', serviceport, 'now open for', token.deviceId);
onDynTcpReadyHelper(serviceport);
});
token.server.on('error', function (e) {
// TODO try again with random port
console.error("Server Error assigning a dynamic port to a new connection:", e);
});
} catch(e) {
// what a wonderful problem it will be the day that this bug needs to be fixed
// (i.e. there are enough users to run out of ports)
console.error("Error assigning a dynamic port to a new connection:", e);
}
} }
remotes[jwtoken] = token; remotes[jwtoken] = token;