2017-07-20 19:42:32 -07:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const libp2p = require('libp2p')
|
|
|
|
const TCP = require('libp2p-tcp')
|
2018-02-19 09:46:11 +00:00
|
|
|
const Mplex = require('libp2p-mplex')
|
2017-07-20 19:42:32 -07:00
|
|
|
const SECIO = require('libp2p-secio')
|
|
|
|
const PeerInfo = require('peer-info')
|
|
|
|
const MulticastDNS = require('libp2p-mdns')
|
|
|
|
const waterfall = require('async/waterfall')
|
|
|
|
const parallel = require('async/parallel')
|
|
|
|
const series = require('async/series')
|
|
|
|
|
|
|
|
class MyBundle extends libp2p {
|
|
|
|
constructor (peerInfo) {
|
|
|
|
const modules = {
|
|
|
|
transport: [new TCP()],
|
|
|
|
connection: {
|
2018-02-19 09:46:11 +00:00
|
|
|
muxer: [Mplex],
|
2017-07-20 19:42:32 -07:00
|
|
|
crypto: [SECIO]
|
|
|
|
},
|
2018-02-15 19:49:41 +01:00
|
|
|
discovery: [
|
|
|
|
new MulticastDNS(peerInfo, { interval: 2000 })
|
|
|
|
]
|
2017-07-20 19:42:32 -07:00
|
|
|
}
|
|
|
|
super(modules, peerInfo)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function createNode (callback) {
|
|
|
|
let node
|
|
|
|
|
|
|
|
waterfall([
|
|
|
|
(cb) => PeerInfo.create(cb),
|
|
|
|
(peerInfo, cb) => {
|
|
|
|
peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
|
|
|
|
node = new MyBundle(peerInfo)
|
|
|
|
node.start(cb)
|
|
|
|
}
|
|
|
|
], (err) => callback(err, node))
|
|
|
|
}
|
|
|
|
|
|
|
|
parallel([
|
|
|
|
(cb) => createNode(cb),
|
|
|
|
(cb) => createNode(cb)
|
|
|
|
], (err, nodes) => {
|
|
|
|
if (err) { throw err }
|
|
|
|
|
|
|
|
const node1 = nodes[0]
|
|
|
|
const node2 = nodes[1]
|
|
|
|
|
|
|
|
series([
|
|
|
|
(cb) => node1.once('peer:discovery', (peer) => node1.dial(peer, cb)),
|
|
|
|
(cb) => setTimeout(cb, 500)
|
|
|
|
], (err) => {
|
|
|
|
if (err) { throw err }
|
|
|
|
|
2018-02-22 07:06:21 +00:00
|
|
|
// Subscribe to the topic 'news'
|
2018-02-15 20:15:18 +01:00
|
|
|
node1.pubsub.subscribe('news',
|
2018-02-16 18:04:10 +00:00
|
|
|
(msg) => console.log(msg.from, msg.data.toString()),
|
2018-02-15 20:15:18 +01:00
|
|
|
() => {
|
|
|
|
setInterval(() => {
|
2018-02-22 07:06:21 +00:00
|
|
|
// Publish the message on topic 'news'
|
|
|
|
node2.pubsub.publish(
|
|
|
|
'news',
|
|
|
|
Buffer.from('Bird bird bird, bird is the word!'),
|
|
|
|
() => {}
|
|
|
|
)
|
2018-02-15 20:15:18 +01:00
|
|
|
}, 1000)
|
2018-02-16 18:04:10 +00:00
|
|
|
}
|
2018-02-15 20:15:18 +01:00
|
|
|
)
|
2017-07-20 19:42:32 -07:00
|
|
|
})
|
|
|
|
})
|