diff --git a/README.md b/README.md index ae9f3ee..7408d9f 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,10 @@ dial uses the best transport (whatever works first, in the future we can have so - `protocol` - `callback` +### `swarm.listen(callback)` + +Start listening on all added transports that are available on the current `peerInfo`. + ### `swarm.handle(protocol, handler)` handle a new protocol. diff --git a/package.json b/package.json index 3b4f634..3d40e22 100644 --- a/package.json +++ b/package.json @@ -79,4 +79,4 @@ "Pau Ramon Revilla ", "Richard Littauer " ] -} \ No newline at end of file +} diff --git a/src/index.js b/src/index.js index 19662d8..136e055 100644 --- a/src/index.js +++ b/src/index.js @@ -217,6 +217,14 @@ function Swarm (peerInfo) { msS.handle(conn) } + function availableTransports (pi) { + const addrs = pi.multiaddrs + return Object.keys(self.transports).filter((ts) => { + // Only listen on transports we actually have addresses for + return self.transports[ts].filter(addrs).length > 0 + }) + } + // higher level (public) API this.dial = (pi, protocol, callback) => { if (typeof protocol === 'function') { @@ -279,7 +287,7 @@ function Swarm (peerInfo) { } function attemptDial (pi, cb) { - const tKeys = Object.keys(self.transports) + const tKeys = availableTransports(pi) nextTransport(tKeys.shift()) function nextTransport (key) { @@ -366,6 +374,14 @@ function Swarm (peerInfo) { } } + // Start listening on all available transports + this.listen = (callback) => { + parallel(availableTransports(peerInfo).map((ts) => (cb) => { + // Listen on the given transport + this.transport.listen(ts, {}, null, cb) + }), callback) + } + this.handle = (protocol, handler) => { this.protocols[protocol] = handler } diff --git a/test/09-swarm-with-muxing.node.js b/test/09-swarm-with-muxing.node.js index 90b1a45..ce20c7b 100644 --- a/test/09-swarm-with-muxing.node.js +++ b/test/09-swarm-with-muxing.node.js @@ -66,8 +66,8 @@ describe('high level API - with everything mixed all together!', function () { parallel([ (cb) => swarmA.transport.listen('tcp', {}, null, cb), - (cb) => swarmB.transport.listen('tcp', {}, null, cb), - (cb) => swarmC.transport.listen('tcp', {}, null, cb) + (cb) => swarmB.transport.listen('tcp', {}, null, cb) + // (cb) => swarmC.transport.listen('tcp', {}, null, cb) ], done) }) @@ -86,12 +86,16 @@ describe('high level API - with everything mixed all together!', function () { parallel([ (cb) => swarmB.transport.listen('ws', {}, null, cb), - (cb) => swarmC.transport.listen('ws', {}, null, cb), + // (cb) => swarmC.transport.listen('ws', {}, null, cb), (cb) => swarmD.transport.listen('ws', {}, null, cb), (cb) => swarmE.transport.listen('ws', {}, null, cb) ], done) }) + it('listen automatically', (done) => { + swarmC.listen(done) + }) + it('add spdy', () => { swarmA.connection.addStreamMuxer(spdy) swarmB.connection.addStreamMuxer(spdy)