How to Broadcast Messages to Multiple WebSocket Clients in Python
How to Create a Simple WebSocket Server in Python With websockets WebSockets allow real-time communication between a client and a server with minimal overhead. In this guide, you'll learn how to create a simple WebSocket server in Python using the native websockets library. 1. Install the websockets Library pip install websockets 2. Writing a Basic WebSocket Server Here's how to set up a basic WebSocket server that echoes messages back to the client: import asyncio import websockets async def echo(websocket, path): async for message in websocket: await websocket.send(f"Echo: {message}") start_server = websockets.serve(echo, "localhost", 8765) asyncio.get_event_loop().run_until_complete(start_server) print("WebSocket server running on ws://localhost:8765") asyncio.get_event_loop().run_forever() This server listens on port 8765 and simply echoes back any message it receives. 3. Connecting to the Server (Client Example) To test it, here’s a quick client implementation: import asyncio import websockets async def hello(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: await websocket.send("Hello Server!") response = await websocket.recv() print(f"Received: {response}") asyncio.run(hello()) When you run this client, it will send a message and print the echoed response. 4. Graceful Shutdown To cleanly shut down the server, you'll want to wrap the server in a context and cancel tasks properly. This becomes important for production scenarios or testing workflows. Conclusion This setup gives you the building blocks of a WebSocket-based application using Python's native websockets library. From here, you can extend it to support multiple clients, broadcast messages, or integrate with existing backend systems. If this post helped you, consider supporting me: buymeacoffee.com/hexshift
How to Create a Simple WebSocket Server in Python With websockets
WebSockets allow real-time communication between a client and a server with minimal overhead. In this guide, you'll learn how to create a simple WebSocket server in Python using the native websockets
library.
1. Install the websockets
Library
pip install websockets
2. Writing a Basic WebSocket Server
Here's how to set up a basic WebSocket server that echoes messages back to the client:
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
await websocket.send(f"Echo: {message}")
start_server = websockets.serve(echo, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
print("WebSocket server running on ws://localhost:8765")
asyncio.get_event_loop().run_forever()
This server listens on port 8765 and simply echoes back any message it receives.
3. Connecting to the Server (Client Example)
To test it, here’s a quick client implementation:
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
await websocket.send("Hello Server!")
response = await websocket.recv()
print(f"Received: {response}")
asyncio.run(hello())
When you run this client, it will send a message and print the echoed response.
4. Graceful Shutdown
To cleanly shut down the server, you'll want to wrap the server in a context and cancel tasks properly. This becomes important for production scenarios or testing workflows.
Conclusion
This setup gives you the building blocks of a WebSocket-based application using Python's native websockets
library. From here, you can extend it to support multiple clients, broadcast messages, or integrate with existing backend systems.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift