Python client-server Socket Programming

In this Python Socket Programming article we want to learn about Python client-server Socket Programming, so Python is popular programming language with different types of applications. one of the feature of Python is socket programming, which involves establishing a connection between client and server over network. in this article we want to learn how to create client-server application using Python socket programming, but first of all let’s talk about socket programming.

 

What is Socket Programming ?

Socket programming is a way to communicate between two computers over a network. socket is a combination of an IP address and port number that represents specific process running on the computer. in Python we can use socket module to establish a connection between client and server.

 

Python client-server Socket Programming

Let’s create simple client-server application that will allow a client to connect to a server and send message. server will receive the message and send a response back to the client.

 

This is code for the server:

In the above code first we have imported socket module and sets the HOST and PORT variables. socket.AF_INET parameter is used to specify IP version, and socket.SOCK_STREAM parameter is used to specify type of the socket which is TCP socket.

s.bind((HOST, PORT)) line binds socket to the HOST and PORT. s.listen() line sets the socket to listen for incoming connections. when a client connects s.accept() function is called to accept the connection. conn variable is new socket object that is used to communicate with the client.

while loop receives data from the client using conn.recv(1024) function. 1024 parameter specifies the maximum amount of data to be received at once. if there is no data loop breaks. otherwise server sends data back to the client using conn.sendall(data.upper()) function. upper() function is used to convert the message to uppercase before sending it back to the client.

 

 

This is the code for client:

So in the client code first we have imported socket module and sets the HOST and PORT variables. client connects to the server using s.connect((HOST, PORT)) function. s.sendall() line sends a message to the server. b before the string indicates that it should be converted to bytes before sending. client then receives the response from the server using s.recv() function. and lastly client prints the received data.

 

Note: You can run the code in two separate terminal

 

 

Learn More

Leave a Comment