Python Socket Client Example

In this Python Socket article we want to talk about Python Socket Client Example, so Python is powerful and famous programming language that allows you to build different types of applications, including network applications that can communicate over the internet. in this article we want to talk about Python socket client example and how to use it to build network applications, but first of all let’s talk that what is socket ?

 

 

What is Socket ?

Socket is a software abstraction that represents an endpoint of two way communication link between two programs running on a network. in simpler terms we can say that socket allows two programs to send and receive data between them over a network.

 

 

Python Socket Client Example

Let’s start by building Python socket client that can connect to a server and send and receive data. this code shows simple Python socket client example, this is our client code and save the code in client.py file.

In the above code we have created a socket object using the socket.socket() method. first argument socket.AF_INET specifies the address family (IPv4), and the second argument socket.SOCK_STREAM specifies the socket type (TCP), and after that we have connected to  remote server using the socket.connect() method. server_address variable specifies the IP address and port number of the server, than we send data to the server using the socket.sendall() method. message is encoded as bytes using the encode() method, after that we receives data from the server using socket.recv() method. 1024 argument specifies the maximum amount of data to be received at once, and lastly we print the received data using print() function and close the socket connection.

 

 

Now let’s create our server code, save the file in server.py file

This code creates socket object and binds it to specific address and port, listens for incoming connections and waits for a client to connect. after that the client is connected, it sends  welcome message and receives data from the client before closing the connection. Note that this is very basic example and in practice, you would want to handle multiple client connections, handle errors and exceptions and implement more advanced functionality as needed.

 

 

Run your code in two terminal this is our server terminal.

Python Socket Client Example
Python Socket Client Example

 

 

 

And this is our client terminal

Python Socket Client Example
Python Socket Client Example

 

 

So in this article we learned how to build Python socket example and use it to communicate with remote server over a network. with this knowledge you can now start building your own network applications using Python.

 

 

Learn More

Leave a Comment