diff --git a/README.md b/README.md index 6cb326a..7526798 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,10 @@ Emitted when the writable side is fully closed. Emitted when the readable side is fully closed. +#### `connection.on('timeout')` + +Emitted when the timeout it's reached. Is only a notification, you should end the connection. + #### `connection.close([callback])` Closes the connection. @@ -141,6 +145,10 @@ The callback is called with `callback(err, buffers, lengths)`. End the writable side of the connection. +#### `connection.setTimeout(millis, [callback])` + +Set timeout on the connection. Optionally you can provide an callback. If millis is setted on 0, then it disabled. + ## License MIT diff --git a/lib/connection.js b/lib/connection.js index f443a1c..3ac0b11 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -22,6 +22,7 @@ class Connection extends events.EventEmitter { this._handle = Buffer.alloc(binding.sizeof_turbo_net_tcp_t) this._reads = new RequestQueue(8, 0) this._writes = new RequestQueue(16, binding.sizeof_uv_write_t) + this._timeoutId = false this._finishing = [] this._closing = [] @@ -56,6 +57,8 @@ class Connection extends events.EventEmitter { } _onclose () { + clearTimeout(this._timeoutId) + if (this._server) unordered.remove(this._server.connections, this) this.closed = true this._closing = callAll(this._closing, null) @@ -196,6 +199,16 @@ class Connection extends events.EventEmitter { binding.turbo_net_tcp_write(this._handle, writing.handle, writing.buffer, len) } + setTimeout (millis, cb) { + clearTimeout(this._timeoutId) + + if (millis > 0) { + this._timeoutId = setTimeout(this.emit.bind(this), millis, 'timeout') + if(cb) this.once('timeout', cb) + } + else if(cb) this.removeListener('timeout', cb) + } + close (cb) { if (!cb) cb = noop if (this.closed) return process.nextTick(cb)