-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
55 lines (47 loc) · 1.33 KB
/
main.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
const Libp2p = require('libp2p')
const TCP = require('libp2p-tcp')
const SECIO = require('libp2p-secio')
const MPLEX = require('libp2p-mplex')
const multiaddr = require('multiaddr')
async function main() {
const node = await Libp2p.create({
addresses: {
// add a listen address (localhost) to accept TCP connections on a random port
listen: ['/ip4/127.0.0.1/tcp/0']
},
modules: {
transport: [TCP],
connEncryption: [SECIO],
streamMuxer: [MPLEX]
}
})
// start libp2p
await node.start()
console.log('libp2p has started')
// print out listening addresses
console.log('listening on addresses:')
node.multiaddrs.forEach(addr => {
console.log(`${addr}/p2p/${node.peerId.toB58String()}`)
})
// ping peer if received multiaddr
if (process.argv.length >= 3) {
const peer = process.argv[2]
console.log(`pinging remote peer at ${peer}`)
setInterval(async () => {
const latency = await node.ping(multiaddr(peer))
console.log(`pinged in ${latency}ms`)
}, 2000)
} else {
console.log('no remote peer address given, skipping ping')
}
async function stop() {
console.log('Stopping...');
// stop libp2p
await node.stop()
console.log('libp2p has stopped')
process.exit(0)
}
process.on('SIGTERM', stop)
process.on('SIGINT', stop)
}
main()