Example TCP client and server nodejs

Server:

 

var net = require('net');

var HOST = '192.168.1.33';

var PORT = 8088;

// Create a server instance, and chain the listen function to it

// The function passed to net.createServer() becomes the event handler for the 'connection' event

// The sock object the callback function receives UNIQUE for each connection

net.createServer(function(sock) {

   

    // We have a connection - a socket object is assigned to the connection automatically

    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

   

    // Add a 'data' event handler to this instance of socket

    sock.on('data', function(data) {

       

        console.log('DATA ' + sock.remoteAddress + ': ' + data);

        // Write the data back to the socket, the client will receive it as data from the server

        sock.write('OK');

        

    });

   

    // Add a 'close' event handler to this instance of socket

    sock.on('close', function(data) {

        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);

    });

   

}).listen(PORT, HOST);

 

console.log('Server listening on ' + HOST +':'+ PORT);

 

Client:

 

var net = require('net');

 

var HOST = '192.168.1.33';

var PORT = 8088;

 

var client = new net.Socket();

client.connect(PORT, HOST, function() {

 

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);

    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client

      

    client.write('I am Thor!');

 

});

 

// Add a 'data' event handler for the client socket

// data is what the server sent to this socket

client.on('data', function(data) {

   

    console.log('DATA: ' + data);

    // Close the client socket completely

    client.destroy();

   

});

 

// Add a 'close' event handler for the client socket

client.on('close', function() {

    console.log('Connection closed');

});

 

Run server:

 

D:\codewr\ServerTCP>node serverTCP.js

Server listening on 192.168.1.33:8088

CONNECTED: 192.168.1.33:57694

DATA 192.168.1.33: I am Thor!

CLOSED: 192.168.1.33 57694

 

Run client:

 

D:\codewr\ServerTCP>node clientTCP.js

CONNECTED TO: 192.168.1.33:8088

DATA: OK

Connection closed