JavaScript: a TCP echo server with the net module

TCP gives two programs a reliable stream of bytes. The net module exposes it directly. net.createServer calls your handler for each new connection with a socket, and a socket emits a data event whenever bytes arrive and a close event when the connection ends.

JavaScript
const net = require("node:net");

const server = net.createServer((socket) => {
  socket.on("data", (chunk) => {
    socket.end("echo: " + chunk.toString().trim() + "\n");
  });
});

server.listen(0, "127.0.0.1", () => {
  const client = net.connect(server.address().port, "127.0.0.1", () => {
    client.write("hello\n");
  });
  client.on("data", (reply) => {
    console.log(reply.toString().trim());
  });
  client.on("close", () => server.close());
});
Read the full lesson