Node JS TCP Socket Client Server Example

This example will show you how to use node js to implement TCP socket client server communication. To achieve this you need to import node js built-in net module and use net.createServer method to create a net.Server object as TCP server, and use net.createConnection method to create a net.Socket object as TCP client.

1. Node JS TCP Socket Client Server Example.

node js tcp socket client server example source files

1.1 tcp_socket_server.js

// Import net module.
var net = require('net');

// Create and return a net.Server object, the function will be invoked when client connect to this server.
var server = net.createServer(function(client) {

    console.log('Client connect. Client local address : ' + client.localAddress + ':' + client.localPort + '. client remote address : ' + client.remoteAddress + ':' + client.remotePort);

    client.setEncoding('utf-8');

    client.setTimeout(1000);

    // When receive client data.
    client.on('data', function (data) {

        // Print received client data and length.
        console.log('Receive client send data : ' + data + ', data size : ' + client.bytesRead);

        // Server send data back to client use client net.Socket object.
        client.end('Server received data : ' + data + ', send back to client data size : ' + client.bytesWritten);
    });

    // When client send data complete.
    client.on('end', function () {
        console.log('Client disconnect.');

        // Get current connections count.
        server.getConnections(function (err, count) {
            if(!err)
            {
                // Print current connection count in server console.
                console.log("There are %d connections now. ", count);
            }else
            {
                console.error(JSON.stringify(err));
            }

        });
    });

    // When client timeout.
    client.on('timeout', function () {
        console.log('Client request time out. ');
    })
});

// Make the server a TCP server listening on port 9999.
server.listen(9999, function () {

    // Get server address info.
    var serverInfo = server.address();

    var serverInfoJson = JSON.stringify(serverInfo);

    console.log('TCP server listen on address : ' + serverInfoJson);

    server.on('close', function () {
        console.log('TCP server socket is closed.');
    });

    server.on('error', function (error) {
        console.error(JSON.stringify(error));
    });

});

Below is server side output.

/usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/SocketClientServer/tcp_socket_server.js
TCP server listen on address : {"address":"::","family":"IPv6","port":9999}
Client connect. Local address : ::ffff:127.0.0.1:9999. client remote address : ::ffff:127.0.0.1:51814
Client connect. Local address : ::ffff:127.0.0.1:9999. client remote address : ::ffff:127.0.0.1:51815
Receive client send data : Java is best programming language. , data size : 35
Receive client send data : Node is more better than java. , data size : 31
Client disconnect.
There are 1 connections now. 
Client disconnect.
There are 0 connections now.

1.2 tcp_socket_client.js

// Import net module.
var net = require('net');

// This function create and return a net.Socket object to represent TCP client.
function getConn(connName){

    var option = {
        host:'localhost',
        port: 9999
    }

    // Create TCP client.
    var client = net.createConnection(option, function () {
        console.log('Connection name : ' + connName);
        console.log('Connection local address : ' + client.localAddress + ":" + client.localPort);
        console.log('Connection remote address : ' + client.remoteAddress + ":" + client.remotePort);
    });

    client.setTimeout(1000);
    client.setEncoding('utf8');

    // When receive server send back data.
    client.on('data', function (data) {
        console.log('Server return data : ' + data);
    });

    // When connection disconnected.
    client.on('end',function () {
        console.log('Client socket disconnect. ');
    });

    client.on('timeout', function () {
        console.log('Client connection timeout. ');
    });

    client.on('error', function (err) {
        console.error(JSON.stringify(err));
    });

    return client;
}

// Create a java client socket.
var javaClient = getConn('Java');

// Create node client socket.
var nodeClient = getConn('Node');

javaClient.write('Java is best programming language. ');

nodeClient.write('Node is more better than java. ');

Below is client side output. We can see that two socket connection use different local port to connect same socket server.

/usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/SocketClientServer/tcp_socket_client.js
Connection name : Java
Connection local address : 127.0.0.1:51814
Connection remote address : 127.0.0.1:9999
Connection name : Node
Connection local address : 127.0.0.1:51815
Connection remote address : 127.0.0.1:9999
Server return data : Server received data : Java is best programming language. , send back to client data size : 0
Client socket disconnect. 
Server return data : Server received data : Node is more better than java. , send back to client data size : 0
Client socket disconnect.

Process finished with exit code 0
(Visited 1,127 times, 27 visits today)
READ :   Node JS Callback Example

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.