From 5ddd85e14eb9b94e80676080febdfaa8ad109799 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Sat, 9 Jun 2018 20:54:32 +0000 Subject: [PATCH] reuse port --- lib/relay.js | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/lib/relay.js b/lib/relay.js index 9493702..3289c18 100644 --- a/lib/relay.js +++ b/lib/relay.js @@ -4,6 +4,7 @@ var url = require('url'); var PromiseA = require('bluebird'); var jwt = require('jsonwebtoken'); var Packer = require('proxy-packer'); +var portServers = {}; function timeoutPromise(duration) { return new PromiseA(function (resolve) { @@ -258,9 +259,7 @@ module.exports.create = function (state) { Devices.add(state.deviceLists, domainname, token); }); - function onDynTcpReady() { - var serviceport = this.address().port; - console.info('[DynTcpConn] Port', serviceport, 'now open for', token.deviceId); + function onDynTcpReadyHelper(serviceport) { //token.dynamicPorts.push(serviceport); Devices.add(state.deviceLists, serviceport, token); //var hri = require('human-readable-ids').hri; @@ -300,16 +299,28 @@ module.exports.create = function (state) { //token.dynamicNames = []; var onePortForNow = parseInt(token.ports[0], 10) || 0; - // TODO try again with random port - try { - token.server = require('net').createServer(onDynTcpConn).listen(onePortForNow, onDynTcpReady); - token.server.on('error', function (e) { - 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); + if (portServers[onePortForNow]) { + //token.ports = []; + token.server = portServers[onePortForNow]; + token.server.on('connection', onDynTcpConn); + onDynTcpReadyHelper(onePortForNow); + } else { + try { + token.server = require('net').createServer(onDynTcpConn).listen(onePortForNow, function () { + var serviceport = this.address().port; + 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;