-
Notifications
You must be signed in to change notification settings - Fork 473
/
Copy pathdialer.js
58 lines (47 loc) · 1.41 KB
/
dialer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'use strict'
/* eslint-disable no-console */
/*
* Dialer Node
*/
const PeerId = require('peer-id')
const createLibp2p = require('./libp2p-bundle')
const pipe = require('it-pipe')
async function run() {
const [dialerId, listenerId] = await Promise.all([
PeerId.createFromJSON(require('./id-d')),
PeerId.createFromJSON(require('./id-l'))
])
// Dialer
const dialerNode = await createLibp2p({
addresses: {
listen: ['/ip4/0.0.0.0/tcp/0']
},
peerId: dialerId
})
// Add peer to Dial (the listener) into the PeerStore
const listenerMultiaddr = '/ip4/127.0.0.1/tcp/10333/p2p/' + listenerId.toB58String()
// Start the dialer libp2p node
await dialerNode.start()
console.log('Dialer ready, listening on:')
dialerNode.multiaddrs.forEach((ma) => console.log(ma.toString() +
'/p2p/' + dialerId.toB58String()))
// Dial the listener node
console.log('Dialing to peer:', listenerMultiaddr)
const { stream } = await dialerNode.dialProtocol(listenerMultiaddr, '/echo/1.0.0')
console.log('nodeA dialed to nodeB on protocol: /echo/1.0.0')
pipe(
// Source data
['hey'],
// Write to the stream, and pass its output to the next function
stream,
// Sink function
async function (source) {
// For each chunk of data
for await (const data of source) {
// Output the data
console.log('received echo:', data.toString())
}
}
)
}
run()