Client Server Communication with Python Socket Programming

Client Server Communication

A client server communication is a request-response process between two host machines one being a client machine which sends a message as a request to another host being the server machine and the server machine in return replies the clients machine as  a response.

In this post, we would demonstrate the step-by-step process of this communication using basic python socket programming with TCP and UDP protocols. 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. It is assumed that the Server Machine is pre-configured with CentOS Linux Server Operating System. The Server runs a python code which keeps the server ready to receive incoming requests from clients. The server is identified by the IP address of its network interface card.

Client: The Client is a machine which sends requests to server and awaits a response to its request from the server. It is assumed that the client machine is pre-configured 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:  A pair of two simple network application programmes are coded on server and client machines which communicate with each other other by writing to and reading from their sockets.

Socket: The socket can be understood 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. Each socket is identified by a port numbetr assigned to it.

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

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

The following steps would be followed 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

If python is successfully installed, it will 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’ representing python file and 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, it will 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’ representing python file and 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!!

Watch the demonstration of above process in following video:

 

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

The two machines should be on same network. IT means that the two machines would be connected with wire using a cable, hub, or switch with each other. The Two machines may also be connected through wi-fi modem as a wireless network connection with each other. 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

The above saved network configurations would be displayed in terminal.

Network Setup on Client Machine:

Each client machine would 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

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

ifconfig

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 means client machine is able to send an ICMP message to server machine and get a reply back from the server 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 means server machine is able to send an ICMP message to client machine and get a reply back from the client machine successfully.

The following image display a successful client server network communication.

ping-client-server.png

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 and the socket at server is identified by Port = 12000 for socket at server.

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 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

The process mentioned in Step-3 above can be executed 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 and the socket at server is identified by Port = 12000 for socket at server.

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 the firewall has been successfully reloaded with new configuration. Execute the “UDPServer.py” code using the following code:

python UDPServer.py

The screen should 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()

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. 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. 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 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:

 

We hope the above information was useful for you. If you liked this article, click the Like button. If you find it useful, Share it with your friends. If you have suggestions for improvements, please leave your valuable feedback or suggestions as Comment.

Subscribe our YouTube Channel to receive latest Video updates. You can also find us on Quora, Facebook, Twitter, Tumblr and Reddit.

About Techsolveprac 17 Articles
A blogger and a YouTuber

1 Comment

Leave a Reply