How to Create a TCP Server in Node.js

Cover Image for How to Create a TCP Server in Node.js

In this article, we will look at how to create a simple TCP server in Node.js. TCP is one of the most common transport layer protocols. It provides a reliable way to send 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.

Installing Node.js:

If you don't have Node.js installed yet, download and install it from the official website.

Creating the Project:

Create a new folder for your project and navigate into it:

mkdir tcp-server
cd tcp-server

Create a file named server.js.

Import the net module. This module does not require installation as it comes with Node.js.

const net = require('net');

Call the createServer method. It creates a server object.

const net = require('net');
const server = net.createServer();

Add a callback to the createServer method. This callback is invoked when the connection event is emitted. This event occurs when a new connection is established with the server. This event returns an object that we name socket. This socket object is an instance of net.Socket.

const net = require('net');
const server = net.createServer((socket) => {
  console.log('Client connected');
});

We can send data to the socket using the write method. We pass it a string of our choice, and it is sent to the client.

const net = require('net');
const server = net.createServer((socket) => {
  console.log('Client connected');

  socket.write('Hello from TCP server!');
});

The data event is triggered when data is received from the client.

const net = require('net');
const server = net.createServer((socket) => {
  console.log('Client connected');

  socket.write('Hello from TCP server!');

  socket.on('data', (data) => {
    console.log('Received:', data.toString());
  });
});

The end event occurs when the socket is fully closed. This means the communication has ended.

const net = require('net');
const server = net.createServer((socket) => {
  console.log('Client connected');

  socket.write('Hello from TCP server!');

  socket.on('data', (data) => {
    console.log('Received:', data.toString());
  });

  socket.on('end', () => {
    console.log('Client disconnected');
  });

  // Handle errors
  socket.on('error', (err) => {
    console.error('Error:', err.message);
  });
});

Set the port and address where the server will listen.

const PORT = 3500;
const HOST = '0.0.0.0';

Finally, to start the server, use the .listen() method. It takes the port number and address. Now our server is running and waiting for new connections.

const net = require('net');
const server = net.createServer((socket) => {
  console.log('Client connected');

  socket.write('Hello from TCP server!');

  socket.on('data', (data) => {
    console.log('Msg from client:', data.toString());
  });

  socket.on('end', () => {
    console.log('Client disconnected');
  });

  // Handle errors
  socket.on('error', (err) => {
    console.error('Error:', err.message);
  });
});

const PORT = 3500;
const HOST = '0.0.0.0';

server.listen(PORT, HOST);

The listen method also takes a callback argument that is invoked when the listening event is emitted, indicating that the server has started listening for incoming connections. We use this event to print a message letting us know that the server is up and running.

server.listen(PORT, HOST, () => {
  console.log(`Server listening on ${HOST}:${PORT}`);
});

Running the Server:

Start the server using the following command:

node server.js

You should see the message:

Server listening on 0.0.0.0:3500

Connecting to the Server:

To test our TCP server, we can use the telnet command. Open a new terminal and run the following command:

telnet 0.0.0.0 3500

You should see the message:

Hello from TCP server!

Alternatively, we can write a small file client.js to test our server.

const net = require("net");

const client = net.connect({ port: 3500 }, () => {
  console.log("Connection established");
  client.write("Hello from client");
});

client.on("data", (data) => {
  console.log("Msg from server:", data.toString());
});

client.on("end", () => {
  console.log("Disconnected from server");
});

Run it using:

node client.js

Conclusion:

In this article, we created a simple TCP server in Node.js that accepts connections from clients, processes data, and sends responses. This is a basic example that can be expanded and improved based on your needs. You can add authentication, data storage, command processing, and much more. The full code for this example is available on GitHub Gist.

If you have any questions or suggestions, feel free to reach out to me on social media. Happy coding!