Skip to content

Commit

Permalink
Graceful server shutdown with bonjour unpublish.
Browse files Browse the repository at this point in the history
  • Loading branch information
hackergrrl committed Jun 30, 2017
1 parent 2104494 commit 7fdc470
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
9 changes: 8 additions & 1 deletion bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,16 @@ switch (args._[2]) {
})
break
case 'share':
createServer({port:port}, function (err, server) {
var server = createServer({port:port}, function (err, server) {
console.log('listening on http://0.0.0.0:' + port)
})
process.on('SIGINT', function () {
console.log('\nUnpublishing mDNS..')
server.terminate(function () {
console.log('Goodbye!')
process.exit()
})
})
break
default:
printUsage()
Expand Down
9 changes: 8 additions & 1 deletion mdns-swarm.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ module.exports = function (opts) {

var bonjour = Bonjour()
var bonjourBrowser = null
var bonjourService = null
var bonjourName = 'friendpm' + (''+Math.random()).substring(2, 8)

function mdnsInit () {
Expand All @@ -30,14 +31,16 @@ module.exports = function (opts) {

function mdnsBroadcast () {
debug('bonjour :: publishing')
var service = bonjour.publish({ name: bonjourName, type: 'friendpm', port: opts.port })
bonjourService = bonjour.publish({ name: bonjourName, type: 'friendpm', port: opts.port })
}

function mdnsSearch (foundCb) {
debug('bonjour :: searching')
return bonjour.find({ type: 'friendpm' })
}

mdnsInit()

// 3 seconds to look for peers; be quick!
var readyTime = Date.now() + 1000 * 3

Expand Down Expand Up @@ -120,5 +123,9 @@ module.exports = function (opts) {
}
}

reg.close = function (done) {
bonjourService.stop(done)
}

return reg
}
6 changes: 3 additions & 3 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ module.exports = function (opts, done) {
router.addRoute('/-/user/org.couchdb.user\::user', onAddUser)

var cache = require('./local-cache')({port:opts.port})
var swarm = require('./mdns-swarm')({skipPublish:opts.skipPublish})
var swarm = require('./mdns-swarm')(opts)

var server = http.createServer(function (req, res) {
debug(req.method.toUpperCase() + ' ' + req.url)
Expand All @@ -43,9 +43,9 @@ module.exports = function (opts, done) {
}
})

server.terminate = function () {
server.terminate = function (done) {
this.close()
if (bonjourBrowser) bonjourBrowser.stop()
swarm.close(done)
}

server.on('error', function (err) {
Expand Down

0 comments on commit 7fdc470

Please sign in to comment.