diff --git a/README.md b/README.md index 9dc765086..9a19a049e 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,7 @@ Exposed as `eio` in the browser standalone build. - `onlyBinaryUpgrades` (`Boolean`): whether transport upgrades should be restricted to transports supporting binary data (`false`) - `forceNode` (`Boolean`): Uses NodeJS implementation for websockets - even if there is a native Browser-Websocket available, which is preferred by default over the NodeJS implementation. (This is useful when using hybrid platforms like nw.js or electron) (`false`, NodeJS only) - `localAddress` (`String`): the local IP address to connect to + - `autoUnref` (`Boolean`): whether the transport should be `unref`'d upon creation. This calls `unref` on the underyling timers and sockets so that the program is allowed to exit if they are the only timers/sockets in the event system. - **Polling-only options** - `requestTimeout` (`Number`): Timeout for xhr-polling requests in milliseconds (`0`) - **Websocket-only options** diff --git a/lib/socket.js b/lib/socket.js index 721093f1d..7a3d42603 100644 --- a/lib/socket.js +++ b/lib/socket.js @@ -70,6 +70,7 @@ class Socket extends Emitter { perMessageDeflate: { threshold: 1024 }, + autoUnref: false, transportOptions: {} }, opts @@ -200,6 +201,9 @@ class Socket extends Emitter { }) .on("close", function() { self.onClose("transport close"); + }) + .on("open", function() { + if (this.opts.autoUnref) transport.unref(); }); } @@ -422,6 +426,9 @@ class Socket extends Emitter { this.pingTimeoutTimer = setTimeout(() => { this.onClose("ping timeout"); }, this.pingInterval + this.pingTimeout); + if (this.opts.autoUnref) { + this.pingTimeoutTimer.unref(); + } } /** diff --git a/lib/transport.js b/lib/transport.js index eb864dc6d..dc0335d29 100644 --- a/lib/transport.js +++ b/lib/transport.js @@ -46,6 +46,16 @@ class Transport extends Emitter { return this; } + /** + * Unrefs the transport + * + * @api public + */ + unref() { + this.doUnref(); + return this; + } + /** * Closes the transport. * diff --git a/lib/transports/polling.js b/lib/transports/polling.js index edf812a12..582f0a3f2 100644 --- a/lib/transports/polling.js +++ b/lib/transports/polling.js @@ -23,6 +23,16 @@ class Polling extends Transport { this.poll(); } + /** + * Ensure that event loop is not kept open only by this transport. + * No-op for polling transports at present. + * + * @api private + */ + doUnref() { + return; + } + /** * Pauses polling. * diff --git a/lib/transports/websocket.js b/lib/transports/websocket.js index 39a6c9fef..63ec47af2 100644 --- a/lib/transports/websocket.js +++ b/lib/transports/websocket.js @@ -95,6 +95,15 @@ class WS extends Transport { this.addEventListeners(); } + /** + * Unrefs socket. + * + * @api private + */ + doUnref() { + this.ws._socket.unref(); + } + /** * Adds event listeners to the socket *