How to Build a TCP Application With Node.js on ECS
Learn how to create a working TCP application which accepts TCP client connections, listens for data on them, and echoes it back to the client.
Join the DZone community and get the full member experience.
Join For FreePrerequisites
Before you start the process, you will need a machine running a Linux/Unix distribution such as Ubuntu or macOS, a code editor/IDE with Node.js installed on it and a basic working knowledge of Node.js.
Creating a TCP Server
To begin, create a directory where you would like to store your application. For this tutorial, we will create our application in ~/nodejs-tcp-app
.
In this tutorial, we will be doing most of our work with the terminal and also, use nano editor
in the terminal ensuring the process remains the same for all the platforms.
To start, open your terminal:
mkdir ~/nodejs-tcp-app
Now, switch to the newly created directory and run npm init
to create the package.json file.
cd ~/nodejs-tcp-app && npm init
Now, the terminal will prompt for basic info about the project, so add the name, author, and main file as server.js
and create the file. You should see the package.json
file in the directory now.
Next, we will create the server.js
file which will have the code for our TCP Server.
Now, enter the following command in the same directory which will create the server.js
file and open the text editor to write the code.
nano server.js
To start with, we'll import the net
module which comes pre-shipped in Node.js and define the port and the host to run the server and then create an instance of the server.
const net = require('net');
//define host and port to run the server
const port = 8080;
const host = '127.0.0.1';
//Create an instance of the server
const server = net.createServer();
//Start listening with the server on given port and host.
server.listen(port,host,function(){
console.log(`Server started on ${host}:${port}`);
});
This is the basic building block of our application and should be enough to start the TCP server.
Next, we need to add a listener on the connection which the client connects.
Edit the server declaration to add a connection listener function called onClientConnection
and then declare the function at the bottom.
const net = require('net');
//define host and port to run the server
const port = 8080;
const host = '127.0.0.1';
//Create an instance of the server
const server = net.createServer(onClientConnection);
//Start listening with the server on given port and host.
server.listen(port,host,function(){
console.log(`Server started on port ${port} at ${host}`);
});
//Declare connection listener function
function onClientConnection(sock){
//Log when a client connnects.
console.log(`${sock.remoteAddress}:${sock.remotePort} Connected`);
//Listen for data from the connected client.
sock.on('data',function(data){
//Log data from the client
console.log(`${sock.remoteAddress}:${sock.remotePort} Says : ${data} `);
//Send back the data to the client.
sock.write(`You Said ${data}`);
});
//Handle client connection termination.
sock.on('close',function(){
console.log(`${sock.remoteAddress}:${sock.remotePort} Terminated the connection`);
});
//Handle Client connection error.
sock.on('error',function(error){
console.error(`${sock.remoteAddress}:${sock.remotePort} Connection Error ${error}`);
});
};
So in the onClientConnection
function, we expect the connection object sock
and then create three event listeners namely data
, close
and error
.
In the data
event listener, we console log the data received from the client and send it back to the client, and in the close
event listener, we handle the connection termination and console log the same. error
event listener handles connection error from the client.
This should complete our server.js
code and now, we have a working TCP application which accepts TCP client connections, listens for data on them and echoes it back to the client. Now, save the file and exit the nano editor.
See Node.js TCP App Development on ECS to create our TCP client using the same module.
Published at DZone with permission of Leona Zhang. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments