Skip to content

Commit b129cf3

Browse files
committed
fix: destroy & end work as no-op on closed streams
Fixes Rapsssito#145
1 parent 57dc527 commit b129cf3

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

src/Socket.js

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -291,27 +291,33 @@ export default class Socket extends EventEmitter {
291291
}
292292

293293
/**
294-
* @param {string | Buffer | Uint8Array} data
294+
* Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.
295+
*
296+
* @param {string | Buffer | Uint8Array} [data]
295297
* @param {BufferEncoding} [encoding]
296298
*/
297299
end(data, encoding) {
298300
if (data) {
299301
this.write(data, encoding, () => {
300302
Sockets.end(this._id);
301303
});
302-
} else {
303-
this._clearTimeout();
304-
Sockets.end(this._id);
304+
return this;
305305
}
306+
if (this._pending || this._destroyed) return this;
307+
308+
this._clearTimeout();
309+
Sockets.end(this._id);
306310
return this;
307311
}
308312

313+
/**
314+
* Ensures that no more I/O activity happens on this socket. Destroys the stream and closes the connection.
315+
*/
309316
destroy() {
310-
if (!this._destroyed) {
311-
this._destroyed = true;
312-
this._clearTimeout();
313-
Sockets.destroy(this._id);
314-
}
317+
if (this._pending || this._destroyed) return this;
318+
this._destroyed = true;
319+
this._clearTimeout();
320+
Sockets.destroy(this._id);
315321
return this;
316322
}
317323

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

336342
const generatedBuffer = this._generateSendBuffer(buffer, encoding);
337343
this._writeBufferSize += generatedBuffer.byteLength;

0 commit comments

Comments
 (0)