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')
|
2020-05-15 15:37:47 +02:00
|
|
|
const { NOISE } = require('libp2p-noise')
|
2019-07-31 18:47:30 +02:00
|
|
|
const Gossipsub = require('libp2p-gossipsub')
|
2020-08-24 11:58:02 +01:00
|
|
|
const uint8ArrayFromString = require('uint8arrays/from-string')
|
2020-08-25 16:48:04 +02:00
|
|
|
const uint8ArrayToString = require('uint8arrays/to-string')
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2019-12-16 22:28:35 +00:00
|
|
|
const createNode = async () => {
|
|
|
|
const node = await Libp2p.create({
|
2020-05-15 15:37:47 +02:00
|
|
|
addresses: {
|
|
|
|
listen: ['/ip4/0.0.0.0/tcp/0']
|
|
|
|
},
|
2019-12-16 22:28:35 +00:00
|
|
|
modules: {
|
|
|
|
transport: [TCP],
|
|
|
|
streamMuxer: [Mplex],
|
2020-10-07 16:16:36 +02:00
|
|
|
connEncryption: [NOISE],
|
2019-12-16 22:28:35 +00:00
|
|
|
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(),
|
2020-04-24 16:10:40 +01:00
|
|
|
createNode()
|
2019-12-16 22:28:35 +00:00
|
|
|
])
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2020-05-15 15:37:47 +02:00
|
|
|
// Add node's 2 data to the PeerStore
|
|
|
|
node1.peerStore.addressBook.set(node2.peerId, node2.multiaddrs)
|
|
|
|
await node1.dial(node2.peerId)
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2020-08-25 16:48:04 +02:00
|
|
|
node1.pubsub.on(topic, (msg) => {
|
|
|
|
console.log(`node1 received: ${uint8ArrayToString(msg.data)}`)
|
2019-12-16 22:28:35 +00:00
|
|
|
})
|
2020-08-25 16:48:04 +02:00
|
|
|
await node1.pubsub.subscribe(topic)
|
2017-07-20 19:42:32 -07:00
|
|
|
|
2020-12-04 14:53:05 +01:00
|
|
|
// Will not receive own published messages by default
|
2020-08-25 16:48:04 +02:00
|
|
|
node2.pubsub.on(topic, (msg) => {
|
|
|
|
console.log(`node2 received: ${uint8ArrayToString(msg.data)}`)
|
2017-07-20 19:42:32 -07:00
|
|
|
})
|
2020-08-25 16:48:04 +02:00
|
|
|
await node2.pubsub.subscribe(topic)
|
2019-12-16 22:28:35 +00:00
|
|
|
|
|
|
|
// node2 publishes "news" every second
|
|
|
|
setInterval(() => {
|
2020-08-24 11:58:02 +01:00
|
|
|
node2.pubsub.publish(topic, uint8ArrayFromString('Bird bird bird, bird is the word!'))
|
2019-12-16 22:28:35 +00:00
|
|
|
}, 1000)
|
2020-04-24 16:10:40 +01:00
|
|
|
})()
|