Block Chain - Server Setup08 Dec 2017
Each Node in a block chain has its own copy of block chain. Therefore, it must be able to provide that block chain to whenever requested. Also, all the nodes interact amongst each other to make sure everyone has the lastest copy of the block chain. Therefore, each node will run two servers. Firstly, one HTTP server to provide a web interface for the users to query the block chain or add some entry to the transaction. Second, one peer to peer server to interact with other nodes.
NOTE: We will not handle peers or messages from peers in this part of the tutorial. That will be covered in a later part after all the block chain utility functions are added. We will just setup the server in this one.
Importing required packages and setting up the server.
- Express is a web application framework for Node.js
- BodyParser is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
- Path module provides utilities for working with file and directory paths.
Then we created an instance of express and stored it in a variable called ‘app’.
app.set() is used to define a constant in the app. Where ever http port number will be required, it will be called using
app.get(). For now only one route for
'/' is added which return simple text “Hello Block Chain”. Now try running the server using either of the following commands.
Visit the url
http://localhost:4001/ and you should text “Hello Block Chain”.
Peer to Peer server
Now that we have a working http server running on localhost port
4001, let us start a peer to peer server too. Firstly, import the required packages.
Now, set a port for this server using
Now, start a websocket server.
index.js looks something like this now.
That’s all for this part. We have setup both our servers for a node. The
HTTP server is running on port
P2P server is running on port
4002. We haven’t yet handled the connection request or incoming messages on the
P2P server as that will come in a later part of this tutorial. In the next part, we will be coding the utility function for our block chain and hopefully, will have a working block chain on a single server.
Next -> Block Chain - Utility Functions
Previous -> Block Chain - Hello World