Python WebSocket – Practical Server / Client example

A WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It’s designed to enable real-time, two-way communication between a client (typically a web browser) and a server, allowing both parties to send and receive data asynchronously without the overhead of repeatedly establishing and closing connections.

Unlike the traditional request-response model of HTTP, where a client sends a request to a server and waits for a response, WebSockets allow ongoing communication where both the client and the server can initiate messages independently. This makes WebSockets ideal for applications that require real-time updates, such as chat applications, online gaming, financial trading platforms, collaborative tools, and more.

This example assumes you have the WebSockets and AsyncIO libraries installed. If not, you can install it using:

pip install websockets 
pip install asyncio

We recommend using a Python Virtual Environment (venv) if you experiment with this.

Here is the guides:

asyncio supports asynchronous programming, allowing you to write concurrent code using asynchronous I/O operations, coroutines, and event loops.

Python WebSocket Server

Python websocket server server.py

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        message = "Responding from the CodeTryout server.py: ", message
        await websocket.send(message)

start_server = websockets.serve(echo, "localhost", 8077)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Python WebSocket Client

Python websocket client – client.py

import asyncio
import websockets

async def hello():
    async with websockets.connect("ws://localhost:8077") as websocket:
        await websocket.send("Hello, CodeTryout!")
        response = await websocket.recv()
        print(response)

asyncio.get_event_loop().run_until_complete(hello())

This client connects to the WebSocket server running on localhost at port 8077, sends a message, and waits for a response.

Testing Python WebSocket Server – Client Communication

First, you need to run the server.py, then open another instance for client.py.

Typical response:

PS C:\Users\devops\DEMO> python .\client.py
Responding from the CodeTryout server.py: Hello, CodeTryout!

WebSocket is a two-way communication protocol, so the server and client can send and receive messages asynchronously. This is just a simple example, and you can build more complex applications using WebSocket for real-time communication.

Key features of WebSockets include:

  1. Full-Duplex Communication: Both the client and the server can send and receive messages simultaneously without having to wait for a response before sending another message.
  2. Low Latency: WebSockets offer low latency communication, making them suitable for applications that require real-time updates.
  3. Efficient: The protocol is more efficient than traditional HTTP requests, as it doesn’t involve the overhead of repeatedly opening and closing connections.
  4. Persistent Connection: Once established, the WebSocket connection remains open until explicitly closed by either the client or the server, enabling continuous communication without the need to reconnect.
  5. Bi-Directional Data: Data can flow in both directions, allowing the client to send data to the server and vice versa.
  6. Standardized Protocol: WebSockets are based on a standardized protocol that is supported by modern web browsers and many server-side frameworks and libraries.
  7. Cross-Domain Communication: WebSockets can be used for cross-domain communication, provided that the server supports the appropriate security mechanisms.

Overall, WebSockets are a powerful way to build interactive and dynamic web applications requiring real-time communication and updates between clients and servers.

Python websockets and asyncio modules

The Python websockets library extends the standard asyncio module, which supports WebSocket communication. WebSockets provide a two-way communication channel for real-time data exchange between a client and a server. The websockets library simplifies the implementation of WebSocket servers and clients, and it integrates smoothly with the asyncio framework. The asyncio module, which is part of the Python standard library, is an asynchronous programming library that allows for efficient concurrent execution of coroutines and tasks. This makes it ideal for handling I/O-bound operations like network communication. When used together, websockets and asyncio enable the development of scalable and responsive applications that depend on WebSocket technology for interactive and asynchronous communication between clients and servers.