Skip to content

Commit

Permalink
browser: add support for down event
Browse files Browse the repository at this point in the history
  • Loading branch information
watson committed Dec 29, 2015
1 parent d3e735b commit ccae34a
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ Options are the same as given in the `browser.find` function.

Emitted every time a new service is found that matches the browser.

#### `Event: down`

Emitted every time an existing service emmits a goodbye message.

#### `browser.services`

An array of services known by the browser to be online.
Expand Down
27 changes: 27 additions & 0 deletions lib/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ Browser.prototype.start = function () {
var self = this

this._onresponse = function (packet) {
goodbyes(self._name, packet).forEach(self._removeService.bind(self))

var matches = buildServicesFor(self._name, packet)
if (matches.length === 0) return

Expand All @@ -70,6 +72,31 @@ Browser.prototype._addService = function (service) {
this.emit('up', service)
}

Browser.prototype._removeService = function (fqdn) {
var service, index
this.services.some(function (s, i) {
if (s.fqdn === fqdn) {
service = s
index = i
return true
}
})
if (!service) return
this.services.splice(index, 1)
this._serviceMap[fqdn] = false
this.emit('down', service)
}

function goodbyes (name, packet) {
return packet.answers.concat(packet.additionals)
.filter(function (rr) {
return rr.name === name && rr.type === 'PTR' && rr.ttl === 0
})
.map(function (rr) {
return rr.data
})
}

function buildServicesFor (name, packet) {
var records = packet.answers.concat(packet.additionals).filter(function (rr) {
return rr.ttl > 0 // ignore goodbye messages
Expand Down
19 changes: 19 additions & 0 deletions test/bonjour.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,25 @@ test('bonjour.find', function (bonjour, t) {
bonjour.publish({ name: 'Baz', type: 'test', port: 3000, txt: { foo: 'bar' } }).on('up', next())
})

test('bonjour.find - down event', function (bonjour, t) {
var service = bonjour.publish({ name: 'Foo Bar', type: 'test', port: 3000 })

service.on('up', function () {
var browser = bonjour.find({ type: 'test' })

browser.on('up', function (s) {
t.equal(s.name, 'Foo Bar')
service.stop()
})

browser.on('down', function (s) {
t.equal(s.name, 'Foo Bar')
bonjour.destroy()
t.end()
})
})
})

test('bonjour.findOne - callback', function (bonjour, t) {
var next = afterAll(function () {
bonjour.findOne({ type: 'test' }, function (s) {
Expand Down

0 comments on commit ccae34a

Please sign in to comment.