2018-10-19 17:37:34 +02:00
|
|
|
/* eslint-disable no-console */
|
2017-07-20 19:42:32 -07:00
|
|
|
'use strict'
|
|
|
|
|
2019-12-16 22:28:35 +00:00
|
|
|
const Libp2p = require('../../')
|
2017-07-20 19:42:32 -07:00
|
|
|
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')
|
2019-07-31 18:47:30 +02:00
|
|
|
const Gossipsub = require('libp2p-gossipsub')
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2019-12-16 22:28:35 +00:00
|
|
|
const createNode = async () => {
|
|
|
|
const peerInfo = await PeerInfo.create()
|
|
|
|
peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
|
|
|
|
|
|
|
|
const node = await Libp2p.create({
|
|
|
|
peerInfo,
|
|
|
|
modules: {
|
|
|
|
transport: [TCP],
|
|
|
|
streamMuxer: [Mplex],
|
|
|
|
connEncryption: [SECIO],
|
|
|
|
pubsub: Gossipsub
|
2017-07-20 19:42:32 -07:00
|
|
|
}
|
2019-12-16 22:28:35 +00:00
|
|
|
})
|
2018-06-28 10:06:25 +02:00
|
|
|
|
2019-12-16 22:28:35 +00:00
|
|
|
await node.start()
|
|
|
|
return node
|
2017-07-20 19:42:32 -07:00
|
|
|
}
|
|
|
|
|
2019-12-16 22:28:35 +00:00
|
|
|
;(async () => {
|
|
|
|
const topic = 'news'
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2019-12-16 22:28:35 +00:00
|
|
|
const [node1, node2] = await Promise.all([
|
|
|
|
createNode(),
|
|
|
|
createNode(),
|
|
|
|
])
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2019-12-16 22:28:35 +00:00
|
|
|
await node1.dial(node2.peerInfo)
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2019-12-16 22:28:35 +00:00
|
|
|
await node1.pubsub.subscribe(topic, (msg) => {
|
|
|
|
console.log(`node1 received: ${msg.data.toString()}`)
|
|
|
|
})
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2019-12-16 22:28:35 +00:00
|
|
|
await node2.pubsub.subscribe(topic, (msg) => {
|
|
|
|
console.log(`node2 received: ${msg.data.toString()}`)
|
2017-07-20 19:42:32 -07:00
|
|
|
})
|
2019-12-16 22:28:35 +00:00
|
|
|
|
|
|
|
// node2 publishes "news" every second
|
|
|
|
setInterval(() => {
|
|
|
|
node2.pubsub.publish(topic, Buffer.from('Bird bird bird, bird is the word!'))
|
|
|
|
}, 1000)
|
|
|
|
})();
|