6: Networking with other peers

Great, we now how a working chat app however it is not that interesting yet. First of all we can only chat with ourself and even worse we can only see the data in the same process 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 connections connecting us to various users all interested in a specific topic.

To achieve this, we'll use a module called discovery-swarm which in turn uses discovery-channel.

This module has three strategies to connect the swarm of peers:

  1. Search the local network. discovery-channel uses a module called 'dns-discovery' that has the ability to make queries in the local network using multicast dns (MDNS).
  2. Search the internet using a well-known server. The next phase is to search using dns, also with dns-discovery.
  3. If these methods fail, it looks in a DHT (distributed hashtable). For this, discovery-channel uses bittorrent-dht.

The third approach uses "bootstrap nodes". The bootstrap nodes function like known peers beforehand, that we use to start to know others and like this form 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 discovery-swarm a unique key that other peers using your app can use to locate each other.

Exercise

Create a discovery.js file:

var discovery = require('discovery-swarm')

var swarm = discovery()

swarm.join('my-p2p-app-{put-your-name-here}')

// this event is fired every time you find and connect to a new peer also on the same key
swarm.on('connection', function (connection, info) {
  // `info `is a simple object that describes the peer we connected to
  console.log('found a peer', info)
  // `connection` is a duplex stream that you read from and write to
})

Extra credit

Once you solve this exercise continue to exercise 7a