From 63005ee10bca50946b04fad39175fdf0c3e68b06 Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Mon, 29 Dec 2014 21:30:03 -0800 Subject: [PATCH] dgram: close() should accept a callback Like net, http, and https server.close, and socket.end(), etc. PR-URL: https://github.com/iojs/io.js/pull/217 Reviewed-By: Ben Noordhuis --- doc/api/dgram.markdown | 7 ++++--- lib/dgram.js | 4 +++- test/parallel/test-dgram-close.js | 7 ++++++- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/doc/api/dgram.markdown b/doc/api/dgram.markdown index 09bacaf098c..ce205c0f5c6 100644 --- a/doc/api/dgram.markdown +++ b/doc/api/dgram.markdown @@ -82,7 +82,7 @@ are created. ### Event: 'close' -Emitted when a socket is closed with `close()`. No new `message` events will be emitted +Emitted after a socket is closed with `close()`. No new `message` events will be emitted on this socket. ### Event: 'error' @@ -228,9 +228,10 @@ shown below. }); -### socket.close() +### socket.close([callback]) -Close the underlying socket and stop listening for data on it. +Close the underlying socket and stop listening for data on it. If a callback is +provided, it is added as a listener for the ['close'](#dgram_event_close) event. ### socket.address() diff --git a/lib/dgram.js b/lib/dgram.js index 75e494cbf2f..255b9fb5941 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -352,7 +352,9 @@ function afterSend(err) { } -Socket.prototype.close = function() { +Socket.prototype.close = function(callback) { + if (callback) + this.on('close', callback); this._healthCheck(); this._stopReceiving(); this._handle.close(); diff --git a/test/parallel/test-dgram-close.js b/test/parallel/test-dgram-close.js index 14204bf05e4..6ac19339e4d 100644 --- a/test/parallel/test-dgram-close.js +++ b/test/parallel/test-dgram-close.js @@ -32,9 +32,13 @@ buf.fill(42); var socket = dgram.createSocket('udp4'); var handle = socket._handle; var closeEvents = 0; +var closeCallbacks = 0; socket.send(buf, 0, buf.length, common.PORT, 'localhost'); -assert.strictEqual(socket.close(), socket); +assert.strictEqual(socket.close(function() { + ++closeCallbacks; +}), socket); socket.on('close', function() { + assert.equal(closeCallbacks, 1); ++closeEvents; }); socket = null; @@ -48,4 +52,5 @@ setImmediate(function() { process.on('exit', function() { assert.equal(closeEvents, 1); + assert.equal(closeCallbacks, 1); });