Build

Python Network Programming: Client, Server and P2P

5 min read Darryn Campbell on Jan 12, 2024
python-network-programming-client-server-and-p2p-1300x600.png

In this tutorial, you'll gain insights on how to exchange data between a client and a server using Python socket programming and the Socket API. Furthermore, you'll get a chance to delve into the direct exchange of data between two or more Python clients using a hosted provider like PubNub. The source code used in this tutorial can be found within the GitHub repository.

Socket programming establishes a connection between two sockets (a client socket and a server socket), enabling them to communicate bi-directionally in real time. Direct socket connections can significantly enhance all real-time applications such as IoT device control, multiuser collaboration, and blockchain since data can be transmitted or received anytime.

Is Python Suitable for Socket Programming?

Absolutely! Python is an excellent choice for socket programming as it has many built-in modules such as socket, select, and asyncio to create client-server applications.

What are Python Sockets Used For?

Python sockets are used in applications that need to communicate over a network: such as web servers, chat applications, or email clients. They can also be used for data streaming and enterprise solutions. The server program listens and handles incoming connections, whilst the client connects to the server to send and receive data. Python sockets support both TCP—a reliable protocol that ensures in-order packet delivery, and UDP—a connectionless and lightweight protocol for applications where packet loss is acceptable.

How do I Run a Socket Program in Python?

The following guide will walk you through creating a Python client and server which can communicate with each other. To get started, you need to set up your account and initialize PubNub. Then, you can send messages and receive messages from the server. You need to run both programs separately, i.e.:

python myServer.py

python myClient.py

Python Programming Environment Set up

You will need a stable version of Python version 3.x installed on your machine. If you are a Windows user, you have the option of adding Python to your PATH. Additionally, you should use a virtual environment for your project. This is a best practice in Python development which allows for isolated environments per project, reducing the risk of package conflicts.

You will also need a code editor to follow along with this tutorial. Visual Studio Code is a popular open-source and free code editor that supports many languages and frameworks, including Python. VSCode also supports extensions for Python to help with code completion and debugging.

Build and Run a Python Socket Application

Let’s build a straightforward socket application using Python. Python provides a native socket class (socket module), so developers don’t need to depend on external libraries. Begin by setting up the Python socket programming client and server:

Import your Python socket library

Create the file client.py in the project directory. To use sockets, import the Python socket library and create a new socket object that connects to a specified IP address (in this case, localhost on port number 8080, but you can select any ipv4 address). Create a new connection to the socket server, send data to the TCP server, and close the socket connection.

Your client.py file should look like this:

You will need a socket server to listen for incoming connections and messages from your client. Create the file server.py and add the following contents:

Server.py binds the socket object to the hostname (localhost) on port 8080 and continually listens for new client connections. When a client connects to this address, the server accepts the connection and reads any data. Once the data is successfully read from the client, the server provides a data response, at which point the client terminates the connection.

Testing your Python Socket Programming

To test this out yourself, open two terminal windows simultaneously. In one window, run:

In the second window, run:

Notice that the server continues running and will establish a new connection every time you run the client and append any new output.

The client will send the "I am CLIENT" string to the server and wait for a reply. The server will read the client’s message, output it to the terminal, and send back a response to the client.

Socket Programming in Python using PubNub

So far, this tutorial has covered exchanging messages between a server and a client, but what if you need to communicate directly between Python clients?

Sending data directly between two or more client devices is tricky because you run into many scaling and security considerations as your number of devices increases. A client-server architecture is used to moderate and manage your client-to-client communication. If you don’t have a web server or you worry about your server scaling to meet your application’s demands, you should opt for a hosted, real-time communication solution such as PubNub. PubNub is a globally distributed and scalable cloud platform, so you don’t have to worry about deploying and maintaining servers. PubNub’s cross-platform SDKs, including Python, can identify users and send messages to specific channels, which only subscribed clients will receive.

Client-to-Client Python Socket Programming

So, how would the simple app presented previously be written with PubNub to exchange messages directly between two clients? It’s essential to understand that although PubNub uses the ‘publish’ and ‘subscribe’ architecture (pub/sub) to send and receive bidirectional messages between endpoints, it still uses sockets behind the scenes. PubNub gives you the benefits of socket communication without worrying about the details of Python network programming and maintaining an always-on connection between your clients regardless of the operating system.

To integrate PubNub into the project, install the PubNub package with pip in the terminal; this will allow you to use the PubNub Python SDK and communicate with the PubNub infrastructure.

You will need to create two clients to connect to and communicate over the PubNub network. Create a file pn_client_1.py and add the following code:

Create the file pn_client_2.py and add the same code as you used for pn_client_1.py

The code above uses ‘demo’ keys, but you should replace those with your own PubNub keys for better security. Also, ensure to store these keys securely and avoid exposing them in public repositories or in the client-side code.

Run both pn_client_1.py and pn_client_2.py simultaneously in two different terminal windows.

Each client initializes its connection to the PubNub network and subscribes to receive new messages whenever they are published to the ‘chan-1’ channel. You can think of this as sending data over a TCP socket in Python; behind the scenes, PubNub is creating and managing the socket for you and routing your message to all clients who are listening to it. Once the remote client receives the message, the received message is displayed on the command line.

And that’s all there is to it!

What is the Alternative to Sockets in Python?

There are several modern alternatives and complements to socket programming, including technologies like HTTP/2, gRPC, and WebSockets. These technologies provide different options for real-time communication in Python applications, enabling developers to choose the most suitable options based on their specific use cases. But keep in mind that you'll find yourself in a similar scaling and distribution problems as Sockets. That's where we can help with these issues, as PubNub is a globally distributed and scalable cloud platform, so you don’t have to worry about deploying and maintaining servers.

For more information on developing with PubNub, check out our range of tutorials and demos.  Alternatively, check out the PubNub interactive tour to understand how our platform provides real-time interactivity to applications. PubNub supports TCP and UDP datagram communication, as well as Linux, Unix, and Windows.

We have an extensive collection of resources on real-time messaging, including expert-written articles and guides on Websockets. Here are some valuable links for you to explore.

We hope this information aids you in your Python socket programming journey with PubNub. Happy coding!