×
Community Blog How to Build a TCP Application with Node.js on ECS

How to Build a TCP Application with Node.js on ECS

In this article, you will get some information for the TCP App Development with Node.js on Alibaba Cloud ECS.

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

Related Blog Posts

Node.js TCP App Development on ECS

To start with the basics, one of the popular open-source JavaScript runtime environments is Node.js that is built on Chrome's V8 JavaScript engine. Node.js is mostly used for building server-side and networking applications. TCP (Transmission Control Protocol) is a networking protocol that enables reliable, ordered and error-checked delivery of a stream of data between applications. For both sides to exchange data streams, a TCP server must accept a TCP connection request, and the connection is then established .

How to Use Node.js to Upload Files to Alibaba Cloud Object Storage

Alibaba Cloud Object Storage Service (OSS) is an easy-to-use service that enables you to store, backup and archive large amounts of data on the cloud. OSS acts as an encrypted central repository from where files can be securely accessed from around the globe. OSS guarantees up to 99.9% availability and is a perfect fit for global teams and international project management.

Related Market Products

There are some products with node.js built by partners can be quickly launched on Alibaba Cloud servers.

Node.js powered by Websoft9(Ubuntu16.04)

Websoft9 Node.js stack is a pre-configured, ready to run image for running Node.js application on Alibaba Cloud.Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine.

Related Documentation

There are some documentation may be useful to you.

Use Node.js SDK

The Alibaba Cloud Node.js Software Development Kit (SDK) allows you to access Alibaba Cloud services such as Elastic Compute Service (ECS), Server Load Balancer (SLB), and CloudMonitor. You can access Alibaba Cloud services without the need to handle API related tasks, such as signing and constructing your requests.

ACM Node.js SDK

ACM Client for Node.js makes it possible to help front-end developers release the front and back ends independently, and separate development from operations, which improves the development efficiency dramatically.

Related Products

There are some products which can help you to optimize your experience on Node.js.

Function Compute

Alibaba Cloud Function Compute is an event-driven and fully-managed compute service. With Function Compute, you can quickly build any type of applications or services without considering management or O&M. You can complete a set of backend services for processing multimedia data even in several days.

Application Configuration Management

Application Configuration Management (ACM), formerly known as Taobao's internal configuration center Diamond, is an application configuration center that enables you to centralize the management of application configurations, and accomplish real-time configuration push in a distributed environment. With ACM, you can greatly reduce the workload of configuration management and enhance service capabilities in scenarios such as microservices, DevOps, and big data.

Related Courses

We also have some courses to help you excel in the tools.

Using Function Compute To Acquire Users Registration Info

This course is designed to assist users who want to get knowledge of serverless computing technology, and who like to use cloud product to apply data processing. In this course, users can understand what is serverless compute, the advantage of function compute, and can apply function compute to satisfy simple business demands.

Using Function Compute To Quickly Build An Image Processing Service

How to deploy an image process service on Alibaba Cloud without even using a server (server-less architecture)? Through this Clouder lesson, you will learn how to conveniently do it with Alibaba Cloud Function Compute.

0 0 0
Share on

Alibaba Clouder

2,599 posts | 762 followers

You may also like

Comments