NodeJS: How to write TCP Server

neotam Avatar

NodeJS: How to write TCP Server

Tags :

This article will help you understand how to write Echo TCP server using Node. TCP is the transport layer protocol which provides services to application layer and takes services from Network Layer. TCP offers the end-to-end commutation and uses the Port Number as address to identify the process in the sending or receiving node.

Example TCP Server Code using Node (Echo TCP Server). Following code receives the data from the connected client and echo’s it back to the sender

const net = require('net');
const port = 8081;
const host = '127.0.0.1';

const server = net.createServer();
server.listen(port, host, () => {
    console.log(TCP Server on ${host}: ${port} );
});

let sockets = [];

server.on('connection', s => {
    console.log('CONNECTED: ' + s.remoteAddress + ':' + s.remotePort);
    sockets.push(s);

    s.on('ready', s=> {
        console.log("Socket is ready to be used")
    })

    s.on('data', function(data) {
        console.log('DATA Received ' + s.remoteAddress + ': ' + data);

        // Write the data back to all the connected, the client will receive it as data from the server
        sockets.forEach(function(s, index, array) {
            s.write(s.remoteAddress + ':' + s.remotePort + " said " + data + '\n');
        });
    });

    // On Connection Close 
    s.on('close', function(data) {
        let index = sockets.findIndex(function(o) {
            return o.remoteAddress === s.remoteAddress && o.remotePort === s.remotePort;
        })
        if (index !== -1) sockets.splice(index, 1);
        console.log('CLOSED: ' + s.remoteAddress + ' ' + s.remotePort);
    });

    
});

How it works ?

const server = net.createServer(); creates the server instance and server.listen opens the TCP socket.. server.on method is the even listener to register events such as connection, ready, data and close to be called when connection is made, socket is ready to be used, when data received and when connection is closed respectively

When data is received on the TCP socket, it is written back on to the connection using write method.

How to run the above code? assuming file name: tcp_server.js

node tcp_server.js

How to connect to the TCP Server ?

Make sure server is running, get the port on which it is running (According to above code Port: 8081)

nc localhost 8081

Bang! start typing to see the echo from the server

Leave a Reply

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