Up until now, the client needed to know the address of the server to be able to connect to it. This is not how p2p systems work. Let's build on the solution for the previous exercise, but make the server discoverable and make the client discover it.
Here is our solution from the previous exercise:
var fs = require('fs')
var net = require('net')
var pump = require('pump')
var server = net.createServer(function (socket) {
var filename = __filename
var file = fs.createReadStream(filename)
console.log('Serving', filename)
// pipe the file to the TCP client
pump(file, socket)
})
server.listen(3000, function () {
console.log('Server is listening on port 3000')
})
Add discoverability to your program so you don't hardcode hostname or port of the server
Use discovery-channel to add discoverabily to your server and client.
The discovery-channel module uses a combination of the multicast-dns and the Bittorrent DHT to make it possible to both discover and announce peers on your local network and even across the internet.
Server example:
var DC = require('discovery-channel')
var channel = DC() // when testing, disable dht `{dht: false}`
// Announce that your server is listening on port 3000
// to anyone asking for 'my-channel-id'
channel.join('my-channel-id', 3000)
Client example:
var DC = require('discovery-channel')
var channel = DC() // when testing, disable dht `{dht: false}`
// Ask to be notified of 'my-channel-id' servers
channel.join('my-channel-id')
channel.once('peer', function (id, peer) {
console.log('Found a new peer:', peer)
})
You can use any channel id you want to. A good idea would be to pass the channel id as a command line argument.
var channelId = process.argv[2]
To avoid spamming the global DHT with a lot of soon to be invalid entries, it's a good idea to disable the global DHT while testing. To do so, initiate discovery-channel like so:
var channel = DC({dht: false})
To test your solution first run the server.
node server.js
then the client.
node client.js
And check that your client successfully finds the server and fetches the file.
When you are done click here to go to the next exercise