Introduction to WebSockets
WebSockets enable real-time, full-duplex communication between clients and servers over a single TCP connection. In this post, we’ll show you how to set up a simple WebSocket server in Python and how to test it using both a Python client and popular command-line utilities like websocat and wscat.
Setting Up a WebSocket Server in Python
We’ll use the websockets library, which provides an easy-to-use asyncio-based WebSocket server implementation. Here’s a simple server (in Python) that listens on port 9090 and prints any received messages with timestamps:
import asyncio
import websockets
from datetime import datetime
async def handler(websocket):
print(f"[{datetime.now().isoformat()}] Client connected from {websocket.remote_address}")
try:
async for message in websocket:
print(f"[{datetime.now().isoformat()}] Received: {message}")
## echo back
await websocket.send(message)
except websockets.exceptions.ConnectionClosed:
print(f"[{datetime.now().isoformat()}] Client disconnected")
async def main():
async with websockets.serve(handler, "0.0.0.0", 9090):
print(f"[{datetime.now().isoformat()}] WebSocket server started on ws://0.0.0.0:9090")
await asyncio.Future() # keep the server running forever
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print(f"\n[{datetime.now().isoformat()}] Server stopped by user")
You would need to install the websockets package first:
pip3 install websockets
Then:
python ws_server.py
Then you will see:
[2025-08-08T12:12:07.868442] WebSocket server started on ws://0.0.0.0:9090
[2025-08-08T12:12:13.871834] Client connected from (‘127.0.0.1’, 34598)
Writing a Simple Python Test Client
To test the server, you can write a Python client that connects, sends a message, and optionally waits for a response:
import asyncio
import websockets
from datetime import datetime
async def test_client():
uri = "ws://localhost:9090"
try:
async with websockets.connect(uri) as websocket:
message = "Hello from test client!"
print(f"[{datetime.now().isoformat()}] Sending: {message}")
await websocket.send(message)
try:
response = await asyncio.wait_for(websocket.recv(), timeout=5)
print(f"[{datetime.now().isoformat()}] Received: {response}")
except asyncio.TimeoutError:
print(f"[{datetime.now().isoformat()}] No response received within timeout.")
except Exception as e:
print(f"Connection failed: {e}")
if name == "main":
asyncio.run(test_client())
Run it:
$ python3 dummy_ws_client.py
[2025-08-08T12:15:08.950121] Sending: Hello from test client!
[2025-08-08T12:15:08.951689] Received: Hello from test client!
Testing with Existing CLI Utilities
Instead of writing a client, you can also use existing tools to interact with your WebSocket server.
websocat
websocat is a command-line utility designed for WebSocket communication, acting like netcat but for WebSockets.
Installation:
On Debian/Ubuntu
sudo apt install websocat
On macOS (using Homebrew)
brew install websocat
Usage:
websocat ws://localhost:9090
You can then type messages, which will be sent to the server. Any server responses will be printed back (echo).
wscat
wscat is a Node.js-based WebSocket command-line client.
Installation via npm:
npm install -g wscat
Usage:
wscat -c ws://localhost:9090
netcat (nc)
While nc is great for raw TCP or UDP testing, it does not support the WebSocket protocol and cannot perform the handshake or frame messages properly. So it won’t work directly with WebSocket servers.
Browser Developer Tools
You can open your browser’s JavaScript console and create a WebSocket client interactively:
let ws = new WebSocket("ws://localhost:9090");
ws.onmessage = (event) => console.log("Received:", event.data);
ws.onopen = () => ws.send("Hello from browser");
Conclusion
Using Python’s websockets library, setting up a WebSocket server is straightforward. Testing your server is also easy with either a custom Python client or existing tools like websocat and wscat. For quick experiments, the browser console is very handy too. Avoid using nc for WebSocket testing as it doesn’t support the protocol.
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: The latest Raspberry Pi 5 comes with up to 16GB of RAM, but it’s a bit pricey.
Next Post: Microsoft's Excel Just Got Smarter: The New Copilot Function
