Skip to content

Commit 17cee4a

Browse files
authored
Merge pull request #407 from libp2p/fix-webrtc-guide
add peer:discovery event listener to webrtc guide
2 parents 623096e + df23440 commit 17cee4a

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

content/guides/getting-started/webrtc.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,13 +428,28 @@ const libp2p = await createLibp2p({
428428
identify: identify(),
429429
},
430430
})
431+
432+
+libp2p.addEventListener('peer:discovery', async (evt) => {
433+
+ // Encapsulate the peer ID to ensure dialing succeeds
434+
+ // Should be removed once https://github.com/libp2p/js-libp2p/issues/3239 is resolved.
435+
+ const maddrs = evt.detail.multiaddrs.map((ma) => ma.encapsulate(`/p2p/${evt.detail.id.toString()}`))
436+
+ console.log(
437+
+ `Discovered new peer (${evt.detail.id.toString()}). Dialling:`, maddrs.map((ma) => ma.toString()),
438+
+ )
439+
+ try {
440+
+ await libp2p.dial(maddrs)
441+
+ } catch (err) {
442+
+ console.error(`Failed to dial peer (${evt.detail.id.toString()}):`, err)
443+
+ }
444+
+})
431445
```
432446

433447
A couple of note-worthy things about these changes:
434448

435449
- The `pubsub` service adds GossipSub protocol capabilities to the node.
436450
- `pubsubPeerDiscovery` depends on the `pubsub` service and introduces the peer discovery mechanism. [GossipSub is a large dependency](https://packagephobia.com/result?p=%40chainsafe%2Flibp2p-gossipsub) making it suboptimal for browser bundles.
437-
- When js-libp2p discovers a new peer (and its multiaddrs), it adds it to the peer store. The connection manager may attempt to dial the newly discovered peer, if the current number of open connections is below the [configured minimum](https://github.com/libp2p/js-libp2p/blob/main/packages/libp2p/src/connection-manager/index.ts#L20-L31). Learn more about the connection manager in [the docs](https://github.com/libp2p/js-libp2p/blob/main/doc/LIMITS.md).
451+
- When js-libp2p discovers a new peer (and its multiaddrs) it emits a `peer:discovery` event.
452+
- To dial a newly discovered peer, add an event listener for the `peer:discovery` event and dial the peer with the `dial` method.
438453
- PubSub peer discovery works well for demos and guides, but its current design is not battle-tested for production use cases.
439454

440455
Next, open two browser tabs of the frontend, and you should see them connected to each other within a couple of seconds 🎉.

0 commit comments

Comments
 (0)