Block Chain - Peer to Peer Communication

Peer to Peer Communication

We will handle the socket io event in this part of the series. Nodes interact with each other if they mine a new block and want to broadcast it, or they want to sync their block chain with other people. Therefore these messages must be handled by the nodes.

We have already imported the required packages in a previous tutorial. Now we need to add an event handler for any new connection request to our web socket server. It is done right after we started our websocket server.

var webServer = new WebSocket.Server({ port: app.get('p2p_port')}, function(){
console.log('P2P server, port: ' + app.get('p2p_port'));
webServer.on('connection', connectionHandler(socket));
function connectionHandler(socket){
//handle connection here
//add a message handler
//add an error handler

webServer.on('connection', function(socket){}) will listen for new connection request. On receiving aconnection request, it will pass the socket information to the function passed as a second argument to it.

Before we move further ahead, we need to create two utility functions send() and broadcast(). These will be used to send messages to connected sockets.

function send( socket, message ){
function broadcast( message ){
for(var i = 0; i < sockets.length ; i++){

We will create an array to save all the connected sockets var sockets = []. Now, lets complete the above function connectionHandler.

var sockets = [];
function connectionHandler(socket){
socket.on('message', function(data){
var msg = JSON.parse(data);
switch (message.greeting){
case "getBlockChain":
send(socket, { greeting: 'responseBlockChain', data: blockChain });
case "responseBlockChain":
console.log("Message code unknown");

function handleBlockChain(){


Now, a question must come to your mind that how will a node find peers to connect to. One of the solutions is to provide a list of peers as a command line argument. Along with the list of peers, we will give the http_port and p2p_port as a command line argument. As a common practice, we will use flags -http_port, -p2p_port and -peers followed by their values.

Next -> Block Chain - Transaction Pool

Previous -> Block Chain - Proof of Work