Pear Baby Rooms 1: your first room
Baby Rooms is our from-absolute-zero track: each lesson is one sitting, ends
with something alive on your screen, and introduces exactly one idea. Lesson
one: a room is just a topic two peers both joined.
Build it
mkdir baby-room && cd baby-room
npm init -y
npm i hyperswarm hypercore-crypto bare bare-process bare-readline
room.js:
const Hyperswarm = require('hyperswarm')
const crypto = require('hypercore-crypto')
const name = process.argv[2] || 'baby-room-hello'
const topic = crypto.hash(Buffer.from('baby-rooms:v1:' + name))
const swarm = new Hyperswarm()
const peers = new Set()
swarm.join(topic, { server: true, client: true })
swarm.on('connection', (socket) => {
peers.add(socket)
console.log('* peer joined (' + peers.size + ' online)')
socket.on('data', (d) => console.log('them:', d.toString().trim()))
socket.on('error', () => {})
socket.on('close', () => { peers.delete(socket); console.log('* peer left') })
})
process.stdin.on('data', (line) => {
for (const p of peers) p.write(line)
})
console.log('room "' + name + '" — waiting for peers…')
Run node room.js secret-club in two terminals (better: two machines, two
networks). When * peer joined prints, type. You are chatting through an
encrypted, holepunched, serverless connection.
What you just learned
- The room name never left your machines — both sides hashed it into a
topic and met at the hash. Unguessable name ⇒ unguessable room.
- There is no room object anywhere. "The room" is only the set of peers
currently joined to the topic. Close both terminals and it does not exist.
- Messages here are ephemeral and unauthenticated — anyone in the room could
claim any name. Fixing that is
lesson 2; making the room remember is
lesson 3.