Build

Python Socket Programming: Server-Client Connection

Darryn Campbell on Jan 12, 2024
Python Socket Programming: Server-Client Connection

Learn to exchange data between a client and server with Python sockets. Try live data transfer between multiple Python clients using a BaaS Edge Messaging Platform like PubNub.

The source code used in this tutorial: GitHub Python Socket server-client code repository

What is Python Socket?

Python Socket is a networking API for bidirectional communication over TCP or UDP. It supports IPv4 (AF_INET), IPv6 (AF_INET6), and socket types like SOCK_STREAM (TCP) and SOCK_DGRAM (UDP). Functions like send(), recv(), bind(), and listen() handle data exchange and connections.

Socket programming establishes a connection between web sockets (client and server sockets), enabling them to communicate bidirectionally in real time. Direct socket connections can significantly reduce app latency, as data can be transmitted or received at any time.

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

How do I Run a Socket Program in Python?

The following guide will walk you through creating a Python client and server that can communicate with each other.

Get started

1. Set up your account and initialize PubNub

2. Now, 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

Use a stable version of Python version 3.x installed on your machine. On Windows, add Python to PATH if needed. Use a virtual environment to isolate dependencies and prevent package conflicts.

You'll need a code editor. Visual Studio Code (VSCode) is a free, open-source option with Python extensions for code completion and debugging.

Build and Run a Python Socket Application

Let’s build a 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 socket in Python

Example of socket import: 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?

Direct client-to-client communication is complex due to scaling and security challenges. A client-server model manages this, but if scaling is a concern, a hosted real-time solution like PubNub is ideal. PubNub's global cloud platform eliminates server maintenance and its cross-platform SDKs, including Python SDK,  JavaScript, Java, and push notifications, enable secure messaging to subscribed channels.

Client-to-Client Python Socket Programming

To build a simple app with PubNub for direct client-to-client messaging (data transmission). PubNub handles socket communication for you, so you can focus on messaging without dealing with network programming or maintaining constant connections across different operating systems.

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?

Modern alternatives to socket programming, like HTTP/2, gRPC, and Websockets, offer different real-time communication options for Python apps. However, these technologies still face scaling and distribution challenges similar to sockets.

PubNub solves these issues by providing a globally distributed, scalable hybrid cloud platform, so you don't have to worry about server deployment or maintenance.

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 hope this information aids you in your Python socket programming journey with PubNub. Happy coding!