From bcc669028ee20d847b90d4f67e9322657f328198 Mon Sep 17 00:00:00 2001 From: David Dias Date: Sat, 28 May 2016 18:20:50 +0100 Subject: [PATCH] add hangup feature --- README.md | 7 +++++++ src/dial.js | 2 +- src/index.js | 14 ++++++++++++++ test/09-swarm-with-muxing.node.js | 22 +++++++++++++++++++++- 4 files changed, 43 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a398208..26d8014 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,13 @@ dial uses the best transport (whatever works first, in the future we can have so - `protocol` - `callback` +### `swarm.hangUp(pi, callback)` + +hangUp the muxedConn we have with the peer + +- `pi` - peer info project +- `callback` + ### `swarm.listen(callback)` Start listening on all added transports that are available on the current `peerInfo`. diff --git a/src/dial.js b/src/dial.js index 92097fe..0f79257 100644 --- a/src/dial.js +++ b/src/dial.js @@ -137,7 +137,7 @@ module.exports = function dial (swarm) { swarm.emit('peer-mux-established', pi) - muxedConn.on('close', () => { + muxedConn.once('close', () => { delete swarm.muxedConns[pi.id.toB58String()] swarm.emit('peer-mux-closed', pi) }) diff --git a/src/index.js b/src/index.js index 0885430..aea2fd1 100644 --- a/src/index.js +++ b/src/index.js @@ -103,6 +103,20 @@ function Swarm (peerInfo) { } } + this.hangUp = (peerInfo, callback) => { + const key = peerInfo.id.toB58String() + if (this.muxedConns[key]) { + const muxer = this.muxedConns[key].muxer + muxer.end() + muxer.on('close', () => { + delete this.muxedConns[key] + callback() + }) + } else { + callback() + } + } + this.close = (callback) => { Object.keys(this.muxedConns).forEach((key) => { this.muxedConns[key].muxer.end() diff --git a/test/09-swarm-with-muxing.node.js b/test/09-swarm-with-muxing.node.js index e41abfd..2c87d9f 100644 --- a/test/09-swarm-with-muxing.node.js +++ b/test/09-swarm-with-muxing.node.js @@ -213,10 +213,30 @@ describe('high level API - with everything mixed all together!', function () { }) }) + it('hangUp', (done) => { + let count = 0 + const ready = () => ++count === 3 ? done() : null + + swarmB.once('peer-mux-closed', (peerInfo) => { + expect(Object.keys(swarmA.muxedConns).length).to.equal(0) + ready() + }) + + swarmA.once('peer-mux-closed', (peerInfo) => { + expect(Object.keys(swarmA.muxedConns).length).to.equal(1) + ready() + }) + + swarmA.hangUp(peerB, (err) => { + expect(err).to.not.exist + ready() + }) + }) + it('close a muxer emits event', (done) => { parallel([ (cb) => swarmC.close(cb), - (cb) => swarmA.once('peer-mux-closed', () => cb()) + (cb) => swarmA.once('peer-mux-closed', (peerInfo) => cb()) ], done) }) })