DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Build a TCP Application With Node.js on ECS

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.

Leona Zhang user avatar by
Leona Zhang
·
May. 10, 19 · Tutorial
Like (1)
Save
Tweet
Share
15.91K Views

Join the DZone community and get the full member experience.

Join For Free

Prerequisites

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.jsfile 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 onClientConnectionand 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.

Transmission Control Protocol Entity component system application Node.js Build (game engine)

Published at DZone with permission of Leona Zhang. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • ChatGPT: The Unexpected API Test Automation Help
  • Top 5 Java REST API Frameworks
  • How To Create and Edit Excel XLSX Documents in Java
  • Express Hibernate Queries as Type-Safe Java Streams

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: