Net
Understand the workings of the net module in Node.js.
We'll cover the following...
TCP
One of the most common transport layer protocols is
net
The net
module provides an asynchronous network API for creating stream-based TCP or
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);
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