Skip to content

Commit

Permalink
Fixes Issue #55, re-registering an exit listener on the process, all …
Browse files Browse the repository at this point in the history
…sockets are now racked and ensured that they are closed out via a single listener
  • Loading branch information
peter-murray authored and peter-murray committed Sep 1, 2015
1 parent 59c4d1d commit 24d9b96
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 6 deletions.
4 changes: 4 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Change Log

## 1.1.2
- Fixes issue #55, upnp searches re-register the exit handler repeatedly causing issues if you use upnp search multiple
times during program execution

## 1.1.1
- Fixes issue #52, respecting the LOCATION value from SSDP lookups

Expand Down
55 changes: 49 additions & 6 deletions hue-api/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ var Q = require("q"),
EventEmitter = require('events').EventEmitter,
util = require("util");

var socketCleanUp = new SocketCleanUp();

/**
* Locates possible Philips Hue Bridges on the network.
* @param timeout The maximum time to wait for responses, or if none provided will default to 5 seconds
Expand Down Expand Up @@ -49,12 +51,8 @@ function SSDPSearch(timeout) {
}
});

// Clean up if close is not called directly
process.on('exit', function () {
if (!self.closed) {
_close(self);
}
});
socketCleanUp.add(self);
socketCleanUp.registerExitListener();
}
SSDPSearch.prototype.__proto__ = EventEmitter.prototype;

Expand All @@ -79,6 +77,7 @@ function _close(target) {
target.closed = true;
target.socket.close();
}
socketCleanUp.remove(target);
}

function _buildSearchPacket(vars) {
Expand Down Expand Up @@ -163,3 +162,47 @@ function _addUnique(array, value) {
array.push(value);
}
}

/**
* A socket register to take care of closing all sockets that are opened, if not already closed
*
* @constructor
*/
function SocketCleanUp() {
this._searches = [];
this._registered = false;
}

SocketCleanUp.prototype.add = function(search) {
this._searches.push(search);
};

SocketCleanUp.prototype.remove = function(search) {
var self = this
, searches = self._searches
, idx = searches.indexOf(search)
;

if (idx > -1) {
searches.splice(idx, 1)
}
};

SocketCleanUp.prototype.finished = function() {
var self = this
, searches = self._searches
;

searches.forEach(function(search) {
_close(search);
});
};

SocketCleanUp.prototype.registerExitListener = function() {
var self = this;

if (! self._registered) {
process.on("exit", self.finished.bind(self));
self._registered = true;
}
};

0 comments on commit 24d9b96

Please sign in to comment.