|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const libp2p = require('libp2p') |
| 4 | +const TCP = require('libp2p-tcp') |
| 5 | +const PeerInfo = require('peer-info') |
| 6 | +const waterfall = require('async/waterfall') |
| 7 | +const parallel = require('async/parallel') |
| 8 | +const pull = require('pull-stream') |
| 9 | + |
| 10 | +class MyBundle extends libp2p { |
| 11 | + constructor (peerInfo) { |
| 12 | + const modules = { |
| 13 | + transport: [new TCP()] |
| 14 | + } |
| 15 | + super(modules, peerInfo) |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +function createNode (callback) { |
| 20 | + let node |
| 21 | + |
| 22 | + waterfall([ |
| 23 | + (cb) => PeerInfo.create(cb), |
| 24 | + (peerInfo, cb) => { |
| 25 | + peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0') |
| 26 | + node = new MyBundle(peerInfo) |
| 27 | + node.start(cb) |
| 28 | + } |
| 29 | + ], (err) => callback(err, node)) |
| 30 | +} |
| 31 | + |
| 32 | +parallel([ |
| 33 | + (cb) => createNode(cb), |
| 34 | + (cb) => createNode(cb) |
| 35 | +], (err, nodes) => { |
| 36 | + if (err) { throw err } |
| 37 | + |
| 38 | + const node1 = nodes[0] |
| 39 | + const node2 = nodes[1] |
| 40 | + |
| 41 | + // exact matching |
| 42 | + node2.handle('/your-protocol', (protocol, conn) => { |
| 43 | + pull( |
| 44 | + conn, |
| 45 | + pull.map((v) => v.toString()), |
| 46 | + pull.log() |
| 47 | + ) |
| 48 | + }) |
| 49 | + |
| 50 | + // semver matching |
| 51 | + /* |
| 52 | + node2.handle('/another-protocol/1.0.1', (protocol, conn) => { |
| 53 | + pull( |
| 54 | + conn, |
| 55 | + pull.map((v) => v.toString()), |
| 56 | + pull.log() |
| 57 | + ) |
| 58 | + }) |
| 59 | + */ |
| 60 | + |
| 61 | + // custom func matching |
| 62 | + /* |
| 63 | + node2.handle('/custom-match-func', (protocol, conn) => { |
| 64 | + pull( |
| 65 | + conn, |
| 66 | + pull.map((v) => v.toString()), |
| 67 | + pull.log() |
| 68 | + ) |
| 69 | + }, (myProtocol, requestedProtocol, callback) => { |
| 70 | + if (myProtocol.indexOf(requestedProtocol)) { |
| 71 | + callback(null, true) |
| 72 | + } else { |
| 73 | + callback(null, false) |
| 74 | + } |
| 75 | + }) |
| 76 | + */ |
| 77 | + |
| 78 | + node1.dial(node2.peerInfo, '/your-protocol', (err, conn) => { |
| 79 | + if (err) { throw err } |
| 80 | + pull(pull.values(['my own protocol, wow!']), conn) |
| 81 | + }) |
| 82 | + |
| 83 | + /* |
| 84 | + node1.dial(node2.peerInfo, '/another-protocol/1.0.0', (err, conn) => { |
| 85 | + if (err) { throw err } |
| 86 | + pull(pull.values(['semver me please']), conn) |
| 87 | + }) |
| 88 | + */ |
| 89 | + |
| 90 | + /* |
| 91 | + node1.dial(node2.peerInfo, '/custom-match-func/some-query', (err, conn) => { |
| 92 | + if (err) { throw err } |
| 93 | + pull(pull.values(['do I fall into your criteria?']), conn) |
| 94 | + }) |
| 95 | + */ |
| 96 | +}) |
0 commit comments