60 lines
1.4 KiB
JavaScript
Raw Normal View History

/* eslint-disable no-console */
2017-07-07 12:55:41 +01:00
'use strict'
const Libp2p = require('../..')
2017-07-07 12:55:41 +01:00
const TCP = require('libp2p-tcp')
2021-08-19 13:18:50 +02:00
const { NOISE } = require('@chainsafe/libp2p-noise')
const MPLEX = require('libp2p-mplex')
2017-07-07 12:55:41 +01:00
const pipe = require('it-pipe')
const concat = require('it-concat')
2017-07-07 12:55:41 +01:00
const createNode = async () => {
const node = await Libp2p.create({
addresses: {
2020-10-15 10:28:01 -05:00
// To signal the addresses we want to be available, we use
// the multiaddr format, a self describable address
listen: ['/ip4/0.0.0.0/tcp/0']
},
modules: {
transport: [TCP],
connEncryption: [NOISE],
streamMuxer: [MPLEX]
2017-07-07 12:55:41 +01:00
}
})
await node.start()
return node
2017-07-07 12:55:41 +01:00
}
function printAddrs (node, number) {
console.log('node %s is listening on:', number)
node.multiaddrs.forEach((ma) => console.log(`${ma.toString()}/p2p/${node.peerId.toB58String()}`))
2017-07-07 12:55:41 +01:00
}
;(async () => {
const [node1, node2] = await Promise.all([
createNode(),
createNode()
])
2017-07-07 12:55:41 +01:00
printAddrs(node1, '1')
printAddrs(node2, '2')
node2.handle('/print', async ({ stream }) => {
const result = await pipe(
stream,
concat
2017-07-07 12:55:41 +01:00
)
console.log(result.toString())
2017-07-07 12:55:41 +01:00
})
node1.peerStore.addressBook.set(node2.peerId, node2.multiaddrs)
const { stream } = await node1.dialProtocol(node2.peerId, '/print')
2017-07-07 12:55:41 +01:00
await pipe(
['Hello', ' ', 'p2p', ' ', 'world', '!'],
stream
)
})();