Node.js was designed from the ground up to do networked programming. In this chapter, we’ll explore Node.js’s built-in support for low-level socket connections. TCP sockets form the backbone of modern networked applications, and understanding them will serve you well as we do more complex networking through the rest of the book.
As you develop socket-based servers and clients, you’ll learn about the following Node.js aspects.
The asynchronous programming techniques we explored in the last chapter will be even more important here. You’ll learn how to extend Node.js classes such as EventEmitter. You’ll create custom modules to house reusable code.
A network connection has two endpoints. A common pattern is for one endpoint to act as the server while the other is the client. We’ll develop both kinds of endpoints in this chapter, as well as a JSON-based protocol for client/server communication.
The JavaScript language has an interesting inheritance model. You’ll learn about Node.js’s utilities for creating class hierarchies.
Testing is important to ensure that our programs behave the way we expect them to. In this chapter, we’ll develop a unit test with a framework called Mocha, which we’ll install with npm.
To begin, we’ll develop a simple and complete TCP server program. Then we’ll iteratively improve the code as we address concerns such as robustness, modularity, and testability.