Skip to content

Commit 953d185

Browse files
dirkmcjacobheun
authored andcommitted
refactor(docs): async await version of examples/echo (#483)
* fix: performance bottleneck in stat.js (#463) Array.shift seems to be very slow, perhaps linear, on some engines, resulting in _update consuming a lot of CPU. * docs(fix): correct docs and example for pnet (#464) * docs(fix): correct docs and example for pnet * docs(fix): correct pnet docs * docs(fix): update README.md language (#468) * docs: reciprocate (#474) * docs(example): fix ipfs cat (#475) `ipfs.files.cat` is incorrect. the correct function is `ipfs.cat` * fix: async await examples/echo * fix: examples readme typos (#481) * fix: simplify libp2p bundle for echo example
1 parent c563e06 commit 953d185

File tree

3 files changed

+66
-118
lines changed

3 files changed

+66
-118
lines changed

examples/echo/src/dialer.js

Lines changed: 38 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -8,51 +8,54 @@
88
const PeerId = require('peer-id')
99
const PeerInfo = require('peer-info')
1010
const Node = require('./libp2p-bundle')
11-
const pull = require('pull-stream')
12-
const async = require('async')
11+
const pipe = require('it-pipe')
1312

14-
async.parallel([
15-
(cb) => PeerId.createFromJSON(require('./id-d'), cb),
16-
(cb) => PeerId.createFromJSON(require('./id-l'), cb)
17-
], (err, ids) => {
18-
if (err) { throw err }
13+
async function run() {
14+
const [dialerId, listenerId] = await Promise.all([
15+
PeerId.createFromJSON(require('./id-d')),
16+
PeerId.createFromJSON(require('./id-l'))
17+
])
1918

2019
// Dialer
21-
const dialerId = ids[0]
2220
const dialerPeerInfo = new PeerInfo(dialerId)
2321
dialerPeerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
2422
const dialerNode = new Node({
2523
peerInfo: dialerPeerInfo
2624
})
2725

28-
// Peer to Dial
29-
const listenerPeerInfo = new PeerInfo(ids[1])
30-
const listenerId = ids[1]
26+
// Peer to Dial (the listener)
27+
const listenerPeerInfo = new PeerInfo(listenerId)
3128
const listenerMultiaddr = '/ip4/127.0.0.1/tcp/10333/p2p/' +
3229
listenerId.toB58String()
3330
listenerPeerInfo.multiaddrs.add(listenerMultiaddr)
3431

35-
dialerNode.start((err) => {
36-
if (err) { throw err }
37-
38-
console.log('Dialer ready, listening on:')
39-
dialerPeerInfo.multiaddrs.forEach((ma) => console.log(ma.toString() +
40-
'/p2p/' + dialerId.toB58String()))
41-
42-
console.log('Dialing to peer:', listenerMultiaddr.toString())
43-
dialerNode.dialProtocol(listenerPeerInfo, '/echo/1.0.0', (err, conn) => {
44-
if (err) { throw err }
45-
46-
console.log('nodeA dialed to nodeB on protocol: /echo/1.0.0')
47-
48-
pull(
49-
pull.values(['hey']),
50-
conn,
51-
pull.collect((err, data) => {
52-
if (err) { throw err }
53-
console.log('received echo:', data.toString())
54-
})
55-
)
56-
})
57-
})
58-
})
32+
// Start the dialer libp2p node
33+
await dialerNode.start()
34+
35+
console.log('Dialer ready, listening on:')
36+
dialerPeerInfo.multiaddrs.forEach((ma) => console.log(ma.toString() +
37+
'/p2p/' + dialerId.toB58String()))
38+
39+
// Dial the listener node
40+
console.log('Dialing to peer:', listenerMultiaddr.toString())
41+
const { stream } = await dialerNode.dialProtocol(listenerPeerInfo, '/echo/1.0.0')
42+
43+
console.log('nodeA dialed to nodeB on protocol: /echo/1.0.0')
44+
45+
pipe(
46+
// Source data
47+
['hey'],
48+
// Write to the stream, and pass its output to the next function
49+
stream,
50+
// Sink function
51+
async function (source) {
52+
// For each chunk of data
53+
for await (const data of source) {
54+
// Output the data
55+
console.log('received echo:', data.toString())
56+
}
57+
}
58+
)
59+
}
60+
61+
run()

examples/echo/src/libp2p-bundle.js

Lines changed: 2 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,12 @@
11
'use strict'
22

33
const TCP = require('libp2p-tcp')
4-
const MulticastDNS = require('libp2p-mdns')
54
const WS = require('libp2p-websockets')
6-
const Bootstrap = require('libp2p-bootstrap')
7-
const spdy = require('libp2p-spdy')
8-
const KadDHT = require('libp2p-kad-dht')
95
const mplex = require('libp2p-mplex')
106
const secio = require('libp2p-secio')
117
const defaultsDeep = require('@nodeutils/defaults-deep')
128
const libp2p = require('../../..')
139

14-
function mapMuxers (list) {
15-
return list.map((pref) => {
16-
if (typeof pref !== 'string') {
17-
return pref
18-
}
19-
switch (pref.trim().toLowerCase()) {
20-
case 'spdy': return spdy
21-
case 'mplex': return mplex
22-
default:
23-
throw new Error(pref + ' muxer not available')
24-
}
25-
})
26-
}
27-
28-
function getMuxers (muxers) {
29-
const muxerPrefs = process.env.LIBP2P_MUXER
30-
if (muxerPrefs && !muxers) {
31-
return mapMuxers(muxerPrefs.split(','))
32-
} else if (muxers) {
33-
return mapMuxers(muxers)
34-
} else {
35-
return [mplex, spdy]
36-
}
37-
}
38-
3910
class Node extends libp2p {
4011
constructor (_options) {
4112
const defaults = {
@@ -44,29 +15,8 @@ class Node extends libp2p {
4415
TCP,
4516
WS
4617
],
47-
streamMuxer: getMuxers(_options.muxer),
48-
connEncryption: [ secio ],
49-
peerDiscovery: [
50-
MulticastDNS,
51-
Bootstrap
52-
],
53-
dht: KadDHT
54-
},
55-
config: {
56-
peerDiscovery: {
57-
mdns: {
58-
interval: 10000,
59-
enabled: false
60-
},
61-
bootstrap: {
62-
interval: 10000,
63-
enabled: false,
64-
list: _options.bootstrapList
65-
}
66-
},
67-
dht: {
68-
kBucketSize: 20
69-
}
18+
streamMuxer: [ mplex ],
19+
connEncryption: [ secio ]
7020
}
7121
}
7222

examples/echo/src/listener.js

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -8,39 +8,34 @@
88
const PeerId = require('peer-id')
99
const PeerInfo = require('peer-info')
1010
const Node = require('./libp2p-bundle')
11-
const pull = require('pull-stream')
12-
const series = require('async/series')
13-
14-
let listenerId
15-
let listenerNode
16-
17-
series([
18-
(cb) => {
19-
PeerId.createFromJSON(require('./id-l'), (err, id) => {
20-
if (err) { return cb(err) }
21-
listenerId = id
22-
cb()
23-
})
24-
},
25-
(cb) => {
26-
const listenerPeerInfo = new PeerInfo(listenerId)
27-
listenerPeerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/10333')
28-
listenerNode = new Node({
29-
peerInfo: listenerPeerInfo
30-
})
31-
32-
listenerNode.on('peer:connect', (peerInfo) => {
33-
console.log('received dial to me from:', peerInfo.id.toB58String())
34-
})
35-
36-
listenerNode.handle('/echo/1.0.0', (protocol, conn) => pull(conn, conn))
37-
listenerNode.start(cb)
38-
}
39-
], (err) => {
40-
if (err) { throw err }
11+
const pipe = require('it-pipe')
12+
13+
async function run() {
14+
const listenerId = await PeerId.createFromJSON(require('./id-l'))
15+
16+
// Listener libp2p node
17+
const listenerPeerInfo = new PeerInfo(listenerId)
18+
listenerPeerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/10333')
19+
const listenerNode = new Node({
20+
peerInfo: listenerPeerInfo
21+
})
22+
23+
// Log a message when we receive a connection
24+
listenerNode.on('peer:connect', (peerInfo) => {
25+
console.log('received dial to me from:', peerInfo.id.toB58String())
26+
})
27+
28+
// Handle incoming connections for the protocol by piping from the stream
29+
// back to itself (an echo)
30+
await listenerNode.handle('/echo/1.0.0', ({ stream }) => pipe(stream.source, stream.sink))
31+
32+
// Start listening
33+
await listenerNode.start()
4134

4235
console.log('Listener ready, listening on:')
4336
listenerNode.peerInfo.multiaddrs.forEach((ma) => {
4437
console.log(ma.toString() + '/p2p/' + listenerId.toB58String())
4538
})
46-
})
39+
}
40+
41+
run()

0 commit comments

Comments
 (0)