From 963026c87cef3641deeada5243f14cedb422feb5 Mon Sep 17 00:00:00 2001 From: "BIALOBOS, Christophe" Date: Thu, 17 Jan 2019 21:09:37 +0100 Subject: [PATCH] The socket reported erroneously timeouts once the connection has been established. This was simply due to inactivity on that socket. I disabled the timeout once the connection is established so that the keepalive mechanism of ember can take place. --- client.js | 16 ++++++++++++---- test/DeviceTree.test.js | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/client.js b/client.js index cba85d5..6dc0d8a 100755 --- a/client.js +++ b/client.js @@ -165,6 +165,12 @@ S101Socket.prototype.connect = function (timeout = 2) { self.emit('connecting'); self.codec = new S101Codec(); + + const connectTimeoutListener = () => { + self.socket.destroy(); + self.emit("error", new Error(`Could not connect to ${self.address}:${self.port} after a timeout of ${timeout} seconds`)); + }; + self.socket = net.createConnection({ port: self.port, host: self.address, @@ -173,6 +179,10 @@ S101Socket.prototype.connect = function (timeout = 2) { () => { winston.debug('socket connected'); + // Disable connect timeout to hand-over to keepalive mechanism + self.socket.removeListener("timeout", connectTimeoutListener); + self.socket.setTimeout(0); + self.keepaliveIntervalTimer = setInterval(() => { try { self.sendKeepaliveRequest(); @@ -204,10 +214,8 @@ S101Socket.prototype.connect = function (timeout = 2) { } ).on('error', (e) => { self.emit("error", e); - }).on("timeout", () => { - self.socket.destroy(); - self.emit("error", new Error(`Could not connect to ${self.address}:${self.port} after a timeout of ${timeout} seconds`)); - }).on('data', (data) => { + }).once("timeout", connectTimeoutListener + ).on('data', (data) => { if (self.isConnected()) { self.codec.dataIn(data); } diff --git a/test/DeviceTree.test.js b/test/DeviceTree.test.js index c0a7c73..0c82675 100644 --- a/test/DeviceTree.test.js +++ b/test/DeviceTree.test.js @@ -41,6 +41,22 @@ describe("DeviceTree", () => { .then(() => tree.disconnect()) }) }); + + it("should not disconnect after 5 seconds of inactivity", () => { + return Promise.resolve() + .then(() => { + let tree = new DeviceTree(LOCALHOST, PORT); + + tree.on("error", error => { + throw error; + }); + + return Promise.resolve() + .then(() => tree.connect()) + .then(() => new Promise(resolve => setTimeout(resolve, 5000))) + .then(() => tree.disconnect()) + }) + }, 7000); }); it("timeout should be taken into account when connecting to unknown host", () => {