Using WebSocket in Python

Using WebSocket in Python

In this article, we will explore how to use WebSockets in Python to improve the interactivity of web applications.

WebSockets are a two-way communication protocol that allows developers to create interactive web applications in real time. Unlike the classic HTTP model, which is stateless in nature, WebSockets maintain an open connection between the client and the server, allowing for more efficient and instant communication. In this article, we will explore how to use WebSockets in Python to improve the interactivity of web applications.

Prerequisites

Before we begin, let's make sure we have Python installed on our system. Additionally, we will install the websockets library using pip:


pip install websockets

Create a WebSocket Server

Let's start by creating a basic WebSocket server using the websockets library. Let's create a file called websocket_server.py and insert the following code:


import asyncio
import websockets

async def handler(websocket, path):
     # The 'websocket' parameter represents the connection to the client.
     # The 'path' parameter represents the path to the request, but we won't use it in this example.
    
     while True:
         # We await messages from the client
         message = await websocket.recv()
        
         # We process the message (add a prefix)
         response = f"Server: {message}"
        
         # We send the response to the client
         await websocket.send(response)

# Let's configure the WebSocket server
start_server = websockets.serve(handler, "localhost", 8765)

# Let's start the server
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

The code above defines a basic WebSocket server that listens on localhost at port 8765. Whenever it receives a message from the client, it responds by adding a "Server:" prefix.

Create a WebSocket Client

Now, let's create a basic WebSocket client. Let's create a file called websocket_client.py and insert the following code:


import asyncio
import websockets

async def hello():
     uri = "ws://localhost:8765"
    
     async with websockets.connect(uri) as websocket:
         # We send a message to the server
         message = "Hello, server!"
         await websocket.send(message)
         print(f"Sent: {message}")
        
         # We get the response from the server
         response = await websocket.recv()
         print(f'Response received: {response}')

# Let's run the WebSocket client
asyncio.get_event_loop().run_until_complete(hello())

The above code defines a WebSocket client that connects to the server on localhost at port 8765. Sends a message to the server, receives the response and prints it to the console.

Run Server and Client

To run the server, open a terminal and run the following command:


python websocket_server.py

Next, we open another terminal and run the client:


python websocket_client.py

We look at the output in the terminals to see the interaction between server and client through the WebSocket connection.

Conclusions

Using WebSockets in Python allows you to implement real-time bidirectional communications between server and client. The websockets library simplifies the implementation of WebSocket servers and clients, allowing developers to create more interactive and dynamic web applications. Experiment further with this technology to integrate real-time functionality into your Python web applications.