Skip to content

Commit

Permalink
fix: destroy & end work as no-op on closed streams
Browse files Browse the repository at this point in the history
Fixes #145
  • Loading branch information
Rapsssito committed Apr 18, 2022
1 parent 57dc527 commit b129cf3
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions src/Socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,27 +291,33 @@ export default class Socket extends EventEmitter {
}

/**
* @param {string | Buffer | Uint8Array} data
* Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.
*
* @param {string | Buffer | Uint8Array} [data]
* @param {BufferEncoding} [encoding]
*/
end(data, encoding) {
if (data) {
this.write(data, encoding, () => {
Sockets.end(this._id);
});
} else {
this._clearTimeout();
Sockets.end(this._id);
return this;
}
if (this._pending || this._destroyed) return this;

this._clearTimeout();
Sockets.end(this._id);
return this;
}

/**
* Ensures that no more I/O activity happens on this socket. Destroys the stream and closes the connection.
*/
destroy() {
if (!this._destroyed) {
this._destroyed = true;
this._clearTimeout();
Sockets.destroy(this._id);
}
if (this._pending || this._destroyed) return this;
this._destroyed = true;
this._clearTimeout();
Sockets.destroy(this._id);
return this;
}

Expand All @@ -331,7 +337,7 @@ export default class Socket extends EventEmitter {
*/
write(buffer, encoding, cb) {
const self = this;
if (this._pending || this._destroyed) throw new Error('Socket is not connected.');
if (this._pending || this._destroyed) throw new Error('Socket is closed.');

const generatedBuffer = this._generateSendBuffer(buffer, encoding);
this._writeBufferSize += generatedBuffer.byteLength;
Expand Down

0 comments on commit b129cf3

Please sign in to comment.