Skip to content

Commit

Permalink
Merge pull request #1 from LuKks/master
Browse files Browse the repository at this point in the history
timeout api
  • Loading branch information
d4tocchini authored Nov 16, 2018
2 parents 8ae9642 + 65ac277 commit 2a56685
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
13 changes: 13 additions & 0 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 2a56685

Please sign in to comment.