Great, we now how a working chat app! However, it is not that interesting yet. First of all, we can only chat with ourselves. Even worse, we can only see the data in the same process to which we are writing. Kinda boring.
Since we are doing a P2P workshop we want to make P2P network connections with each other. Contrary to how we build HTTP services we don't really have a client/server model in P2P. Instead we have what is called a "swarm". A swarm is just a collection of network sockets connecting us to various users all interested in a specific topic.
To achieve this, we'll use a module called hyperswarm
. This module has three strategies to connect the swarm of peers:
dns-discovery
.The third approach uses "bootstrap nodes". Bootstrap nodes are hardcoded peers. We use them so we have a starting point for discovering other peers with the goal of forming our own swarm. In other words, we need to know someone to enter the network. Unlike centralized services, anybody can provide these bootstrap peers, and they don't need to ever see our data.
You give hyperswarm a unique key that other peers using your app can use to locate each other.
Create a discovery.js file:
const Hyperswarm = require('hyperswarm')
const swarm = new Hyperswarm()
const topic = Buffer.from('a49766a23610999dc5dfe05bc37cd98a9911d4b46bd25fc2cd037b9669a1e214', 'hex')
swarm.join(topic)
// this event is fired every time you find and connect to a new peer also on the same key
swarm.on('connection', function (socket, info) {
// `info` is a simple object that describes the peer we connected to
console.log('found a peer', info)
// `socket` is a duplex stream that you read from and write to it, e.g.,
// process.stdin.pipe(socket).pipe(process.stdout)
})
socket
is a duplex stream, so you can use socket.write('hello')
to write data, and listen to it for "data"
events like the other streams we've worked with.Once you solve this exercise continue to exercise 7a