2017-07-07 18:43:15 +01:00
|
|
|
'use strict'
|
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
const Libp2p = require('../../')
|
2017-07-07 18:43:15 +01:00
|
|
|
const TCP = require('libp2p-tcp')
|
2020-01-02 21:51:02 +01:00
|
|
|
const MPLEX = require('libp2p-mplex')
|
|
|
|
const SECIO = require('libp2p-secio')
|
2017-07-07 18:43:15 +01:00
|
|
|
const PeerInfo = require('peer-info')
|
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
const pipe = require('it-pipe')
|
2017-07-07 18:43:15 +01:00
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
const createNode = async () => {
|
|
|
|
const peerInfo = await PeerInfo.create()
|
|
|
|
peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
|
2017-07-07 18:43:15 +01:00
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
const node = await Libp2p.create({
|
|
|
|
peerInfo,
|
|
|
|
modules: {
|
|
|
|
transport: [TCP],
|
|
|
|
streamMuxer: [MPLEX],
|
|
|
|
connEncryption: [SECIO]
|
2017-07-07 18:43:15 +01:00
|
|
|
}
|
2020-01-02 21:51:02 +01:00
|
|
|
})
|
2017-07-07 18:43:15 +01:00
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
await node.start()
|
2017-07-07 18:43:15 +01:00
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
return node
|
|
|
|
}
|
|
|
|
|
|
|
|
;(async () => {
|
|
|
|
const [node1, node2] = await Promise.all([
|
|
|
|
createNode(),
|
|
|
|
createNode()
|
|
|
|
])
|
2017-07-07 18:43:15 +01:00
|
|
|
|
|
|
|
// exact matching
|
2020-01-02 21:51:02 +01:00
|
|
|
node2.handle('/your-protocol', ({ stream }) => {
|
|
|
|
pipe(
|
|
|
|
stream,
|
|
|
|
async function (source) {
|
|
|
|
for await (const msg of source) {
|
|
|
|
console.log(msg.toString())
|
|
|
|
}
|
|
|
|
}
|
2017-07-07 18:43:15 +01:00
|
|
|
)
|
|
|
|
})
|
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
// multiple protocols
|
2017-07-07 18:43:15 +01:00
|
|
|
/*
|
2020-01-02 21:51:02 +01:00
|
|
|
node2.handle(['/another-protocol/1.0.0', '/another-protocol/2.0.0'], ({ protocol, stream }) => {
|
|
|
|
if (protocol === '/another-protocol/2.0.0') {
|
|
|
|
// handle backwards compatibility
|
|
|
|
}
|
2017-07-07 18:43:15 +01:00
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
pipe(
|
|
|
|
stream,
|
|
|
|
async function (source) {
|
|
|
|
for await (const msg of source) {
|
|
|
|
console.log(msg.toString())
|
|
|
|
}
|
|
|
|
}
|
2017-07-07 18:43:15 +01:00
|
|
|
)
|
|
|
|
})
|
|
|
|
*/
|
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
const { stream } = await node1.dialProtocol(node2.peerInfo, ['/your-protocol'])
|
|
|
|
await pipe(
|
|
|
|
['my own protocol, wow!'],
|
|
|
|
stream
|
|
|
|
)
|
2017-07-07 18:43:15 +01:00
|
|
|
|
|
|
|
/*
|
2020-01-02 21:51:02 +01:00
|
|
|
const { stream } = node1.dialProtocol(node2.peerInfo, ['/another-protocol/1.0.0'])
|
2017-07-07 18:43:15 +01:00
|
|
|
|
2020-01-02 21:51:02 +01:00
|
|
|
await pipe(
|
|
|
|
['my own protocol, wow!'],
|
|
|
|
stream
|
|
|
|
)
|
2017-07-07 18:43:15 +01:00
|
|
|
*/
|
2020-01-02 21:51:02 +01:00
|
|
|
})();
|