Chapter 10. Client-server communications using Node.js, TypeScript, and WebSockets

 

This chapter covers

  • Why a blockchain may need a server
  • The longest chain rule
  • How to create a Node.js WebSocket server in TypeScript
  • Practical use of TypeScript interfaces, abstract classes, access qualifiers, enums, and generics

In the previous chapter, you learned that each block miner can take a number of pending transactions, create a valid block that includes the proof of work, and add the new block to the blockchain. This workflow is easy to follow when there is only one miner creating the proof of work. Realistically, there could be thousands of miners around the world trying to find the valid hash for a block with the same transactions, which may cause conflicts.

In this chapter, we’ll use TypeScript to create a server that uses the WebSocket protocol to broadcast messages to the blockchain’s nodes. The web clients can also make requests of this server.

While writing code in TypeScript remains our main activity, we’ll use several JavaScript packages for the first time in this book:

  • ws— A Node.js library that supports the WebSocket protocol
  • express— A small Node.js framework offering HTTP support
  • nodemon— A tool that restarts Node.js-based apps when script file changes are detected
  • lit-html— HTML templates in JavaScript for rendering to the browser’s DOM

These packages are included in the package.json file as dependencies (see section 10.4.2).

10.1. Resolving conflicts using the longest chain rule

10.2. Adding a server to the blockchain

10.3. The project structure

10.4. The project’s configuration files

10.5. A brief introduction to WebSockets

10.6. Reviewing notification workflows

Summary

sitemap