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:
pip install websockets
Step 2: Sending and Receiving Messages on the Server
Below is an example of how to send and receive messages on a WebSocket server:
import asyncio
import websockets
# WebSocket connection handling function
async def handle_connection(websocket, path):
async for message in websocket:
await websocket.send(f"Server received: {message}")
# Initialize the WebSocket server
start_server = websockets.serve(handle_connection, "localhost", 8765)
# Run the server within the event loop
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
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:
import asyncio
import websockets
async def send_and_receive():
async with websockets.connect("ws://localhost:8765") as websocket:
await websocket.send("Hello, WebSocket!")
response = await websocket.recv()
print("Received:", response)
asyncio.get_event_loop().run_until_complete(send_and_receive())
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.