diff --git a/lib/connection.js b/lib/connection.js index b924b807..3728bb59 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -84,6 +84,9 @@ function Connection (options) { this.socketId = 0; + // when true, we end all sockets after the pending notifications reach 0 + this.shutdownPending = false; + events.EventEmitter.call(this); } @@ -99,7 +102,7 @@ Connection.prototype.checkInitialized = function () { }; /** - * You should never need to call this method, initialisation and connection is handled by {@link Connection#sendNotification} + * You should never need to call this method, initialization and connection is handled by {@link Connection#sendNotification} * @private */ Connection.prototype.initialize = function () { @@ -346,7 +349,7 @@ Connection.prototype.socketDrained = function(socket, serviceBuffer) { socket.busy = false; if(this.options.enhanced) { var notification = socket.cachedNotifications[socket.cachedNotifications.length - 1]; - this.emit('transmitted', notification.notification, notification.recipient); + this.emit('transmitted', notification.notification, notification.recipient, socket); } if(serviceBuffer === true && !this.runningOnNextTick) { // There is a possibility that this could add multiple invocations to the @@ -362,6 +365,12 @@ Connection.prototype.socketDrained = function(socket, serviceBuffer) { } this.runningOnNextTick = true; } + if (this.notificationBuffer.length === 0 && this.shutdownPending) { + debug("closing connections"); + for (var i = this.sockets.length - 1; i >= 0; i--) { + this.sockets[i].end(); + } + } }; /** @@ -704,4 +713,11 @@ Connection.prototype.sendNotification = function (notification) { return this.pushNotification(notification, notification.device); }; +/** + * End connetions with APNS once we've finished sending all notifications + */ +Connection.prototype.shutdown = function () { + this.shutdownPending = true; +}; + module.exports = Connection;