Client Server Communication with Python Sockets

Client Server Communication

This article describes the process of simulating client server communication between two systems. The two systems will act as client and server. We will establish the communication by writing code in python language. We will use python sockets (both TCP socket and UDP socket).

A client server communication is a request-response process between two host machines. First being a client machine sends a message as a request to second host. Second host being the server machine in return replies to the clients machine as  a response.

The key terms and configurations used in this post are as explained in detail as following:

Server: The server is a machine which is an “always on host” and ready to accept incoming requests from clients. In this article, we use a Server Machine with CentOS Linux Server Operating System. The Server runs a python code which keeps the server ready to receive incoming requests from clients. The network packets identify the server with the IP address of server’s network interface card.

Client: A Client is a machine which sends requests to server and awaits a response from server. In this article, we use a client machine with Ubuntu Linux Desktop Operating System. The client machine executes a python code each time it needs to send a request to the server.

Python Socket Programming:  We will write a pair of two simple network application programmes on server and client machines. Both machines will communicate with each other other by writing to and reading from their sockets.

Socket: One can understand socket as an entry door to a machine. It is the interface between the transport layer of the network and the application residing on the machine. We will assign a port number to each socket for identification.

TCP Protocol: The Transmission Control Protocol (TCP) is a transport layer protocol. It provides a reliable and connection-oriented services between the communicating machines.

UDP Protocol: The User Datagram Protocol (UDP) is a transport layer protocol. It provides an unreliable and connectionless service between the communicating machines.

We will follow the following steps to implement the client server communication scenario:

Step-1: Install and Check Python on client and server machines

Python installation on Server Machine:

Login to Server machine, open terminal and run the following command:

sudo yum install python

FEnter root password (if asked), press ‘y’ for download and follow on screen instructions till the installation is complete. Upon, completion run the following command to check version of installed python:

python −−version

The console will display the version of python after successfull installation. Subsequently, write a simple “Hello World” Program. Execute this program to check if python codes are executing successfully. Open an editor such as ‘vi’ or ‘gedit’ and create a new file named ‘hello.py’ using:

 

vi hello.py

The above command will create a new file with extension ‘py’. ‘py’ extension represents a python file. Terminal will open the vi editor to write content to the file. Write the following line in the hello.py file:

print (‘Hello World!’)

Press ‘Esc’, then write ‘:wq’ on the vi editor console to write and exit the file.

On console execute the hello.py file using following command:

python hello.py

If the python code is executed successfully, the terminal will display the text line:

Hello World!

Python installation on Client Machine:

Now, Login to Client machine with Ubuntu Desktop Operating System, open terminal and run the following command:

sudo apt-get install python

Enter root password (if asked), press ‘y’ for download and follow on screen instructions till the installation is complete. Upon, completion run the following command to check version of installed python:

python −−version

If python is successfully installed, console will certainly display the version of the installed python. Write and execute a simple Hello World Program to check if python programmes are executing successfully. Open an editor such as ‘vi’ or ‘gedit’ and create a new file named ‘hello.py’ using:

 

vi hello.py

The above command will create a new file with extension ‘py’. “.py” exptesnion represents python file. The terminal will open the vi editor to write content to the file. Write the following line in the hello.py file:

print (‘Hello World!!’)

Press ‘Esc’, then write ‘:wq’ on the vi editor console to write and exit the file.

On console execute the hello.py file using following command:

python hello.py

If the python code is executed successfully, the terminal will certainly display the following text line:

Hello World!!

Watch the demonstration of above process in following video:

 

Step-2: Setup Network Communication between client and server machines

Certainly, the two machines should be on same network. That is to say that the two machines would be connected with wire using a cable, hub, or switch. Alternatively, the Two machines may also be connected through wi-fi modem as a wireless network connection with each other. Most importantly, the two machines should have same series of IP addresses to respond to each other’s ping messages.

Network Setup on Server Machine:

The server machine would be identified by a unique IP Address (192.168.1.2 in our example) on a network.

Login to Server Machine. Go to Network Settings. Select IPV4 settings. Change IPV4 method from automatic to Manual and enter following network details:

Address: 192.168.1.2

Subnet: 255.255.255.0

Gateway: 192.168.1.1

DNS: Automatic

Routes: Automatic

Apply the new settings and exit. Open terminal and check the IP address using following command:

ifconfig

Certainly, the above saved network configurations would be displayed in terminal.

Network Setup on Client Machine:

Each client machine will be identified by a unique IP Address (192.168.1.3 in our example) on a network. Login to Client Machine. Go to Network Settings. Select IPV4 settings. Change IPV4 method from automatic to Manual and enter following network details:

Address: 192.168.1.3

Subnet: 255.255.255.0

Gateway: 192.168.1.1

DNS: Automatic

Routes: Automatic

Subsequently, apply the new settings and exit. Open terminal and check the IP address using following command:

ifconfig

Certainly, the above saved network configurations would be displayed in terminal.

Check Communication between Client and Server Machine:

Open terminal on client machine and type the following:

ping 192.168.1.2

If a proper ping reply without any error is received, it firstly means that client machine is able to send an ICMP message to server machine. Secondly, the client machine is getting back a reply from the server machine successfully.

Now, open terminal in server machine and type the following command:

ping 192.168.1.3

If a proper ping reply without any error is received, it firstly means server machine is able to send an ICMP message to client machine. Secondly, the server machine is getting back a reply from the client machine successfully.

The following image display a successful client server network communication.

client server communication using python sockets

Watch the demonstration of above process in following Video:

 

Step-3: Client Server Communication using Python Socket with TCP Protocol

After setting up the basic network connectivity between client and server machines, proceed with writing and executing python socket code on each machine to communicate with each other using socket and TCP protocol.

In this exercise, the server is identified with IP Address = 192.168.1.2. Whereas, the socket at server is identified by Port = 12000.

Write and Execute Python Socket code with TCP Protocol on Server Machine:

Login to Server Machine, Open Terminal, Create a File named ‘TCPServer.py’ in an editor such as vi or gedit. Lets use gedit to create and open the file as following:

gedit TCPServer.py

The above command will create and open a new python file ‘TCPServer.py’. Write the following lines of code in this file:

from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((”, serverPort))
serverSocket.listen(1)
print ‘Server is Listening for incoming Client Requests!!!’
while True:
connectionSocket, addr = serverSocket.accept()
messagefromclient = connectionSocket.recv(1024)
print ‘Message from Client: ‘, messagefromclient
messagefromserver = raw_input(‘Enter reply message for client: ‘)
connectionSocket.send (messagefromserver)

Note: Line 4 in above code consists of 2 single quotes (‘) and not be mistaken for a single double Quotes (“).

Save and Exit the File.

Open Port 12000 in server’s firewall so that it accepts incoming requests from the network using TCP protocol on this port using the following command:

firewall-cmd –zone=public –permanent –add-port=12000/tcp

Enter password, press enter, on receiving “success” message reload the firewall using the following command:

firewall-cmd –reload

A “success” message the firewall has been successfully reloaded with new configuration. Execute the “TCPServer.py” code using the following code:

python TCPServer.py

The screen should certainly display the message “Server is Listening for incoming Client Requests!!!” as written in your code.

Write and Execute Python Socket code with TCP Protocol on Client Machine:

Login to Client Machine, Open Terminal, Create a File named ‘TCPClient.py’ in an editor such as vi or gedit. Lets use gedit to create and open the file as following:

gedit TCPClient.py

The above command will create and open a new python file ‘TCPClient.py’. Write the following lines of code in this file:

from socket import *
serverName = ‘192.168.1.2’
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
messagetoserver = raw_input(‘Enter Message for Server: ‘)
clientSocket.send(messagetoserver)
replyfromserver = clientSocket.recv(1024)
print ‘Reply Message from Server: ‘, replyfromserver
clientSocket.close()

Save and Exit the File. Execute the “TCPClient.py” code using the following code:

python TCPClient.py

The Client Machine Terminal should display the message “Enter Message for Server: ” as written in your code. Write a message and Hit Enter. The message will be passed to server machine and the client would wait for a response from server. The Server machine will receive and display the message from client on its terminal followed by a message “Enter reply message for client: ” as written in server code. Write a reply message to Client and hit Enter. The message will be replied to client. The client machine will display the message from server and close the connection.

The process can be repeated as many times by executing the “python TCPClient.py” command on client machine. The code on Server machine would keep on running until interrupted by user.

Watch the demonstration of above process in following video:

 

Step-4: Client Server Communication using Python Socket with UDP Protocol

We can also implement the process mentioned in Step-3 above using UDP protocol instead of TCP. After setting up the basic network connectivity between client and server machines, proceed with writing and executing python socket code on each machine to communicate with each other using socket and UDP protocol.

In this exercise, the server is identified with IP Address = 192.168.1.2. Whereas, the socket at server is identified by Port = 12000.

Write and Execute Python Socket code with UDP Protocol on Server Machine:

Login to Server Machine, Open Terminal, Create a File named ‘UDPServer.py’ in an editor such as vi or gedit. Lets use gedit to create and open the file as following:

gedit UDPServer.py

The above command will create and open a new python file ‘UDPServer.py’. Write the following lines of code in this file:

from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind((”, serverPort))
print ‘The Server is ready to receive requests from Clients’
while True:
messagefromclient, clientAddress = serverSocket.recvfrom(2048)
print ‘Message from Client: ‘, messagefromclient
messagetoclient = raw_input(‘Enter Reply Message to Client: ‘)
serverSocket.sendto(messagetoclient, clientAddress)

Note: Line 4 in above code consists of 2 single quotes (‘) and not be mistaken for a single double Quotes (“). Save and Exit the File.

Open Port 12000 in server’s firewall so that it accepts incoming requests from the network using UDP protocol on this port using the following command:

firewall-cmd –zone=public –permanent –add-port=12000/udp

Enter password, press enter, on receiving “success” message reload the firewall using the following command:

firewall-cmd –reload

A “success” message will certainly mean that the firewall has been successfully reloaded with new configuration. Execute the “UDPServer.py” code using the following code:

python UDPServer.py

The screen should certainly display the message “The Server is ready to receive requests from Clients” as written in your code.

Write and Execute Python Socket code with UDP Protocol on Client Machine:

Login to Client Machine, Open Terminal, Create a File named ‘UDPClient.py’ in an editor such as vi or gedit. Lets use gedit to create and open the file as following:

gedit UDPClient.py

The above command will create and open a new python file ‘UDPClient.py’. Write the following lines of code in this file:

from socket import *
serverName = ‘192.168.1.2’
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
messagetoserver = raw_input(‘Enter Message for Server: ‘)
clientSocket.sendto(messagetoserver, (serverName, serverPort))
messagefromserver, serverAddress = clientSocket.recvfrom(2048)
print ‘Reply from Server: ‘, messagefromserver
clientSocket.close()

Finally, save and Exit the File. Execute the “UDPClient.py” code using the following code:

python UDPClient.py

The Client Machine Terminal should display the message “Enter Message for Server: ” as written in your code. Subsequently, write a message and Hit Enter. The message will be passed to server machine and the client would wait for a response from server. The Server machine will receive and display the message from client on its terminal followed by a message “Enter reply message to client: ” as written in server code. Subsequently, write a reply message to Client and hit Enter. The message will be replied to client. The client machine will display the message from server and close the connection.

You can repeat the process as many times by executing the “python UDPClient.py” command on client machine. The code on Server machine would keep on running until interrupted by user.

Watch the demonstration of above process in following video:

Read Even More:

What is a Digital Library or e-Library?

What is a Local Area Network (LAN)

How to use Wireshark?

Windows Inter-Networking Commands?

How to remove Virus from a Flash Drive without Anit-Virus?

What is Cloud Computing?


We hope the above information was useful for you. Alas! Information keeps on updating. Follow us on social media, subscribe to our blog or subscribe our YouTube Channel to receive latest updates.

Be the first to comment

Leave a Reply (if you any question or feedback for us)