Files
pear-docs/howto/connect-to-many-peers-by-topic-with-hyperswarm.md
Sean Zellmer 577c4c1bec Updating guides (1.5.0) (#154)
* Remove `--` for app option passthrough

Changed since `paparam` was used for parsing command line options:
85892a6a32a84ae42a548f8e3ac0b5dbedd70c80
Now uses `cmd.rest` for app args.

* Use `Pear.config.args` for howto scripts

* Update "starting a pear desktop project" guide to match template

* Remove `--no-ask-trust` flag from `pear run` cli doc

This command was replaced by `--no-ask` which was already in the
documentation. Updated a reference to `--no-ask-trust` in the 'Sharing a
Pear Application' guide.

* Fix typos in "Releasing a Pear Application" guide

* Correct application storage folder name in hyperbee howto

* Add missing `test/index.test.js` in project structure for terminal guide

* Remove language about app continuing to run

This is no longer true at least as of pear:
v0.5114.pqbzjhqyonxprx8hghxexnmctw75mr91ewqw5dxe1zmntfyaddqy / v1.5.0

* Fix extra indention in example code for hypercore howto

* Format json in `_template.json` example

* Add instructions to set up a minimal `package.json` for testing template

Without this, the next step of `pear run --dev .` does not work since
`pear` expects a `package.json` file.

* Rename hyperbee reader app in hyperdrive howto to avoid name conflict

Naming only matters if someone is following the guides and starts each
guide from the same root directory. If they do, then `bee-reader-app`
from the hyperdrive conflicts with the `bee-reader-app` from the
hyperbee howto.

* Remove unrelated youtube tutorial from hyperswarm howto

* Update guide/creating-a-pear-init-template.md

Co-authored-by: David Mark Clements <huperekchunow@googlemail.com>

* Fix spelling mistake

Co-authored-by: David Mark Clements <huperekchunow@googlemail.com>

---------

Co-authored-by: David Mark Clements <huperekchunow@googlemail.com>
2024-11-01 19:32:58 +01:00

2.8 KiB

How to connect to many peers by topic with Hyperswarm

In the former example, two peers connected directly using the first peer's public key. Hyperswarm helps to discover peers swarming a common topic, and connect to as many of them as possible. This will become clearer in the Hypercore example, but it's the best way to distribute peer-to-peer data structures.

The Hyperswarm module provides a higher-level interface over the underlying DHT, abstracting away the mechanics of establishing and maintaining connections. Instead, 'join' topics, and the swarm discovers peers automatically. It also handles reconnections in the event of failures.

In the How to connect two Peers by key with Hyperdht, we needed to explicitly indicate which peer was the server and which was the client. By using Hyperswarm, we create two peers, have them join a common topic, and let the swarm deal with connections.

This How-to consists of a single application, peer-app.

Create the peer-app project with the following commands:

mkdir peer-app
cd peer-app
pear init -y -t terminal
npm install hyperswarm hypercore-crypto b4a bare-process

Alter the peer-app/index.js file to the following:

import Hyperswarm from 'hyperswarm'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'
import process from 'bare-process'

const swarm = new Hyperswarm()
Pear.teardown(() => swarm.destroy())

// Keep track of all connections and console.log incoming data
const conns = []
swarm.on('connection', conn => {
  const name = b4a.toString(conn.remotePublicKey, 'hex')
  console.log('* got a connection from:', name, '*')
  conns.push(conn)
  conn.once('close', () => conns.splice(conns.indexOf(conn), 1))
  conn.on('data', data => console.log(`${name}: ${data}`))
  conn.on('error', e => console.log(`Connection error: ${e}`))
})

// Broadcast stdin to all connections
process.stdin.on('data', d => {
  for (const conn of conns) {
    conn.write(d)
  }
})

// Join a common topic
const topic = Pear.config.args[0] ? b4a.from(Pear.config.args[0], 'hex') : crypto.randomBytes(32)
const discovery = swarm.join(topic, { client: true, server: true })

// The flushed promise will resolve when the topic has been fully announced to the DHT
discovery.flushed().then(() => {
  console.log('joined topic:', b4a.toString(topic, 'hex'))
})

In one terminal, open peer-app with pear run --dev .

cd peer-app
pear run --dev .

This will display the topic. Copy/paste that topic into as many additional terminals as desired with pear run --dev . <SUPPLY TOPIC HERE> (assuming that the current working directory of each terminal is the peer-app folder). Each peer will log information about the other connected peers.

Start typing into any terminal, and it will be broadcast to all connected peers.