Vishal
Posted on November 20th
How to create a TCP server with nodeJs
"how to create a TCP server with nodeJs"
How to create a TCP server with nodeJs
Introduction
In this tutorial, we will learn what is TCP server and how can we create a TCP server in nodeJs using net
About TCP server
A TCP server is a type of server that uses the Transmission Control Protocol (TCP) to set up and manage connections with clients over a network. TCP is one of the essential protocols within the Internet Protocol Suite and gives reliable, ordered, and mistakes-checked transport of statistics between packages walking on gadgets linked to a network.
In the case of a TCP server:
- Connection Establishment: The server listens for incoming connection requests from clients. When a client wants to connect to the server, it initiates a connection request. The server acknowledges this request and establishes communication between the server and the client.
- Data exchange: Once a connection is established, the server and client can exchange data in two ways. Data is sent as a stream, consisting of a sequence of bytes. Both the server and the client can send and receive data as needed.
- Disconnected: When the connection session ends, the client or server can initiate disconnect. A message is sent to this other party indicating the intent to close the connection. Upon receiving this message, the client and server release the provisioned resources and neatly close the connection.
TCP servers are commonly used in a variety of networked applications, such as web servers, email servers, file transfer servers, and many others that require reliable, connection-oriented communication protocols are important features of in a client-server architecture, where clients initiate requests and servers respond toward those request
A TCP (Transmission Control Protocol) server is a fundamental aspect of networked structures, facilitating dependable and ordered communication among a couple of devices over a community. As a part of the TCP/IP (Internet Protocol Suite), TCP guarantees the reliable transmission of facts by way of setting up and managing connections among servers and customers.
At its core, a TCP server operates on a connection-oriented version, in which communique periods are set up, facts is exchanged, and connections are terminated in a structured way. The server typically listens for incoming connection requests from clients, waiting to establish new connections. Upon receiving a request, the server accepts it, creating a committed communique channel among the server and the consumer.
Once the connection is hooked up, data change starts. TCP guarantees that information is transmitted reliably, that means it is introduced accurately and in the appropriate order, whilst also handling any ability errors that can arise throughout transmission. This reliability makes TCP suitable for applications wherein information integrity is essential, along with report switch, far off get right of entry to, and internet surfing.
Furthermore, TCP servers guide bidirectional verbal exchange, permitting both the server and the client to send and acquire statistics as wished. This enables real-time interplay among linked gadgets, making TCP servers critical for a huge variety of networked applications.
Additionally, TCP servers control connection termination, making sure that assets are launched correctly once the verbal exchange consultation is whole. This graceful closure of connections enables in correctly handling network sources and ensures that gadgets can handle new connection requests efficaciously.
In precis, TCP servers play a critical role in facilitating reliable and orderly verbal exchange between gadgets on a community. By presenting a sturdy framework for records transmission, TCP servers empower various networked applications to function correctly and securely, forming the backbone of contemporary interconnected structures.
For creating a TCP server with nodeJs make sure NodeJs is installed in your machine
How to install NodeJs on Ubuntu
To install NodeJs on ubuntu follow these steps
Step 1: Update the system
Open your terminal and run this command to check the0 package repository index is up-to-date
sudo apt update
Step 3: Download and Install NodeJs
You can install NodeJs using this command
sudo apt install nodejs
Step3 : Download and install NPM
npm is a package deal supervisor for Node.Js and is usually blanketed with the Node.Js set up. To install npm, you can run:
sudo apt install npm
Step 3: Check Node version
After set up, you can confirm if Node.Js and npm had been installed efficiently with the aid of checking their versions:
node -v
npm -v
Install Node.js using NodeSource Repository
you can install Node.js using the NodeSource repository, it’s provide more up-to-data version.
First, install the NodeSource and the curl utility
sudo apt install curl
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
Once NodeSource and curl installed then install the Node.js and npm
sudo apt install nodejs
sudo apt install npm
After installing check the version to verify
node -v
npm -v
Node version:
v21.1.0
npm version:
10.2.0
Start Creating Server
After installing node and npm, let’s setup our project
First create a file name server.js
touch server.js
After creating a file import the net module using the require function
const net = require("net");
After importing the net, we will use the net.createServer() method to create a TCP server instance. this method takes a callback function as an argument, which will be invoked each time a client connect to the server
const tcpServer = net.createServer(...)
After creating a server we need to write some code to create a working TCP server
const tcpServer = net.createServer(
(socket) => {
console.log('a client connected');
socket.on("data", (clientData) => {
console.log(`client sent ${clientData}`)
})
socket.on('end', () => {
console.log('Client disconnected');
});
}
)
a client connected will be printed when a new user will be connected.
After this all thing, listen our server on a specific port
tcpServer.listen(3000, 'localhost');
Here is our full code
const net = require("net");
const tcpServer = net.createServer(
(socket) => {
console.log('a client connected');
socket.on("data", (clientData) => {
console.log(`client sent ${clientData}`)
})
socket.on('end', () => {
console.log('Client disconnected');
});
}
)
tcpServer.listen(3000, 'localhost');
Our code is done here and not start our server for starting our server we will need to run two commands first command for starting the server and the second for connecting a user with our server
Terminal 1
node server.js
To test the TCP server, we can use netcat (nc) to establish a connection. Run the following command in your terminal:
Terminal 2
nc localhost 3000
This connects to our TCP server running on localhost at port 3000. You can send data to the server, and it will be logged in the server's console.
If you show this message it means everything is ok. The client is successfully connected with the server now send anything from the client (Terminal 2) you will receive that message on server side (Terminal 1)
Terminal 2
Terminal 1
And now everything is done
Congratulations, your TCP server is ready now
Conclusion
In this guide, we've covered the basics of creating a TCP server in Node.js using the net module. You now have the foundation to build more complex networked applications, experiment with different functionalities and explore further possibilities with Node.js networking.
Complete Code
The project is available on our GitHub : https://github.com/piehostHQ/node-tcp
