WebSocket communication allows you to send and receive real-time messages between a server and clients. Here's a detailed guide on how to achieve this in Python using the websockets
library.
Step 1: Install the WebSocket Library
First, install the websockets
library by running the following command in the terminal:
Step 2: Sending and Receiving Messages on the Server
Below is an example of how to send and receive messages on a WebSocket server:
In the code snippet:
-
async def handle_connection(websocket, path):
: This function handles WebSocket connections. When a client sends a message, this function listens and sends a response back. -
async for message in websocket:
: This loop listens for messages from the client through the WebSocket connection. -
await websocket.send(f"Server received: {message}")
: This function sends a response from the server back to the client via the WebSocket connection.
Step 3: Sending and Receiving Messages from the Client
Here's an example of how the client sends and receives messages from the WebSocket server:
In the code snippet:
-
async with websockets.connect("ws://localhost:8765") as websocket:
: This is how the client connects to the WebSocket server. The client establishes a connection to thelocalhost
address and port8765
. -
await websocket.send("Hello, WebSocket!")
: The client sends the messageHello, WebSocket!
to the server. -
response = await websocket.recv()
: The client waits to receive a response from the server via the WebSocket connection.
Conclusion
By following the steps and understanding each part of the example, you've successfully learned how to send and receive messages via WebSocket in Python. This opens up possibilities for creating real-time applications and continuous data exchange between server and clients.