The Complete Beginner's Guide to TCP Server and Client

In this tutorial, I am going to make simple tcp server using NodeJs and and tcp client using NodeJs and Python.

In order to make tcp server using NodeJs, I will use 'net' npm module.

First make a folder, using command

$ mkdir tcp_test 

Then, enter the following  commands sequentially,
 1.$ cd tcp_test
 2.$ npm init #for making NodeJs project
 3. Keep pressing enter leaving all settings default.This will make a file named package.json
 4.$ touch index.js
 5.$ touch client.js
 6.$ touch client.py

Open index.js in your favourite text editor, copy paste following code to make tcp server,

var net = require('net'); //requiring or importing net module
var server = net.createServer(function(socket) {
        socket.write('Echo this message\r\n'); //echo this //message to client
        socket.pipe(socket);
        socket.on('data',function(e){
             console.log(e.toString());
             socket.on('error', function(e) {
                    console.log(e);
             });
        });
});
server.listen(1337, '0.0.0.0');
Now server is ready and print the data to console sent by client.
For client open client.js in text editor, and copy and paste following code,
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
        console.log('Connected');
        client.write('Hello, server! Message from client');
});
client.on('data', function(data) {
        console.log('Message From ' + data);
        client.destroy(); // kill client after server's response
});
client.on('close', function() {
        console.log('Connection closed');
});
NodeJs tcp client is ready now.
To run server $node index.jsand to run client $node client.js
Here is client code in python,

import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 1337
BUFFER_SIZE = 5120
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #making #socket object
s.connect((TCP_IP, TCP_PORT)) #making connection to server
data = "Hello, server! Message from client"
s.send(data) #Sending data
s.close() #closing socket connection
Now we are all set, to run python tcp client, $ python client.py

2 comments:

  1. Replies
    1. Thanks for going through the article.I will keep posting useful stuffs on this blog.

      Delete