Node: How to write TCP client

neotam Avatar

Node: How to write TCP client

This article will help you understand how to write general TCP Client using Node. TCP is the transport layer protocol which provides services to application layer and takes service from Network Layer. TCP offers the end-to-end communication also referred as process to process communication. Port Number is an address used in transport layer to identify the corresponding sending or receiving process.

An example of simple TCP server written in Node

const Net = require('net');

const port = 8081;
const host = '';

const client = new Net.Socket();

// first argument is options and second argument is the connect even listner 
client.connect({ port: port, host: host }), function() {
  // If successfully established a connection with server 
  console.log("TCP connection established with server"); 

  // Up on connection send Hello to server
  client.write("Hello from client"); 

client.on('data', function(chunk) {
    console.log(Data received : ${chunk.toString()}.);

client.on('end', function() {
    console.log('Connection Closed');

// connect even listener 
client.on('connect', function() {
    console.log('Connected to Server');
    client.write('Hello, Welcome!');

How does it work ?

First create the socket using “const client = new Net.Socket();” where client refers the socket created. To connect to the desired server use the connect method with first argument as object representing the host and port of the TCP server. Details about the signature of the method socket.connect where second argument is the connection even lister which will be called upon the successful connection.

Event listeners for the events ‘data’, ‘connect’ and ‘end’ are attached to the client (or socket). Every time data is received, event listener function attached by following code is called

client.on('data', function(chunk) {
    console.log(Data received : ${chunk.toString()}.);

Test the client using the Node Echo Server. Or, you can also use the netcat to run the TCP server as follows

Open the port 8081 using netcat and then run the TCP client to connect and send data

nc -l 8081

Above command opens the socket and listens for the connections. To run tcp_client, assuming file saved as tcp_client.js

node tcp_client.js 

Leave a Reply

Your email address will not be published. Required fields are marked *