Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

timeout api #1

Merged
merged 2 commits into from
Nov 16, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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