Net

Understand the workings of the net module in Node.js.

TCP

One of the most common transport layer protocols is TCPTransmission Control Protocol. It provides a reliable way of sending packets in an ordered and error-checked stream. TCP is connection-oriented, which means that a connection must be established between the client and the server before data can be sent. We will not delve into the details of how that works, as that is beyond the scope here. Still, it is important to know how it works, as it will help us understand the difference between TCP and UDP.

net

The net module provides an asynchronous network API for creating stream-based TCP or IPCInter-Process Communication servers. Let’s see how we can make a simple TCP server. Run the code below.

var net = require("net");

var server = net.createServer();
const port = 3500;

server.on("connection", function (socket) {
  console.log("Client connected from", socket.remoteAddress, socket.remotePort);
  socket.write("Hello from the server!");

  socket.on("data", function (data) {
    console.log("Msg from client:", data.toString());
  });

  socket.on("close", function (err) {
    if (err) {
      console.log("Client disconnected due to error");
    } else {
      console.log("Client disconnected");
    }
  });
});

server.on("listening", function () {
  console.log("Server is listening on port", port);
});

server.listen(port);
Use ctrl + b, followed by a direction key, to switch panes in the terminal

This simple TCP server presents a lot of useful methods of the net module. Let’s explore them further.

The server-side

  • We import the net
...