Designing raw asyncio WebSocket chat server with manual heartbeat
The plan is to implement a ChatServer class managing rooms with thread-safe async locks, handling JSON messages for join/leave/send actions, and running a manual heartbeat per connection by disabling built-in ping/pong and sending pings periodically with timeout. On disconnect or heartbeat failure, the connection cleans up from all rooms. Next step is providing the complete implementation code.
Below is a minimal, “raw” chat server built on top of asyncio and the websockets library. It demonstrates:
- A registry of rooms; each room holds a set of websocket connections.
- A simple JSON protocol for joining/leaving rooms and sending messages.
- A heartbeat loop that periodically sends
ping frames and closes connections that don’t respond (zombie detection).
Save this as, e.g., chat_server.py and run it with Python 3.8+ (install websockets with pip install websockets).
import asyncio
import json
from collections import defaultdict
from typing import Dict, Set
import websockets
from websockets.exceptions import ConnectionClosed
HEARTBEAT_INTERVAL = 20 # seconds between pings
HEARTBEAT_TIMEOUT = 10 # time to wait for pong
class ChatServer:
def __init__(self):
# room name -> set of websocket connections
self.rooms: Dict[str, Set[websockets.WebSocketServerProtocol]] = defaultdict(set)
# websocket connection -> set of room names joined
self.memberships: Dict[websockets.WebSocketServerProtocol, Set[str]] = defaultdict(set)
# a lock to protect room modifications (optional, but safer under concurrency)
self._lock = asyncio.Lock()
async def register(self, ws: websockets.WebSocketServerProtocol, room: str) -> None:
async with self._lock:
self.rooms[room].add(ws)
self.memberships[ws].add(room)
await ws.send(json.dumps({"event": "joined", "room": room}))
async def unregister(self, ws: websockets.WebSocketServerProtocol, room: str) -> None:
async with self._lock:
if room in self.rooms and ws in self.rooms[room]:
self.rooms[room].remove(ws)
if not self.rooms[room]:
del self.rooms[room]
if ws in self.memberships and room in self.memberships[ws]:
self.memberships[ws].remove(room)
await ws.send(json.dumps({"event": "left", "room": room}))
async def broadcast(self, room: str, sender: websockets.WebSocketServerProtocol, message: str) -> None:
# Copy the recipients to avoid holding the lock while sending
async with self._lock:
recipients = list(self.rooms.get(room, []))
# Broadcast in parallel; drop disconnected peers
if not recipients:
return
payload = json.dumps({"event": "message", "room": room, "message": message})
to_remove = []
for peer in recipients:
if peer == sender:
continue # optionally skip echo back to sender
try:
await peer.send(payload)
except ConnectionClosed:
to_remove.append(peer)
# Cleanup any peers that failed
if to_remove:
async with self._lock:
for peer in to_remove:
for r in list(self.memberships.get(peer, [])):
if peer in self.rooms.get(r, set()):
self.rooms[r].remove(peer)
if not self.rooms[r]:
del self.rooms[r]
self.memberships.pop(peer, None)
async def heartbeat(self, ws: websockets.WebSocketServerProtocol) -> None:
"""
Periodically send pings. If a pong isn't received within HEARTBEAT_TIMEOUT,
close the connection.
"""
try:
while True:
await asyncio.sleep(HEARTBEAT_INTERVAL)
ping = ws.ping()
try:
await asyncio.wait_for(ping, timeout=HEARTBEAT_TIMEOUT)
except asyncio.TimeoutError:
# Did not receive pong in time
await ws.close(code=1011, reason="Heartbeat timeout")
break
except ConnectionClosed:
pass # Connection closed, exit heartbeat loop
async def handler(self, ws: websockets.WebSocketServerProtocol, path: str) -> None:
"""
Main connection handler. Expects JSON messages of the form:
{"action": "join", "room": "room1"}
{"action": "leave", "room": "room1"}
{"action": "send", "room": "room1", "message": "Hello"}
"""
# Start the heartbeat task
hb_task = asyncio.create_task(self.heartbeat(ws))
try:
async for raw_message in ws:
try:
data = json.loads(raw_message)
except json.JSONDecodeError:
await ws.send(json.dumps({"error": "invalid_json"}))
continue
action = data.get("action")
room = data.get("room")
if action == "join" and room:
await self.register(ws, room)
elif action == "leave" and room:
await self.unregister(ws, room)
elif action == "send" and room:
msg_text = data.get("message", "")
await self.broadcast(room, ws, msg_text)
else:
await ws.send(json.dumps({"error": "invalid_action"}))
except ConnectionClosed:
pass # Normal disconnection
finally:
# Cancel heartbeat task
hb_task.cancel()
# Cleanup memberships
async with self._lock:
for room in list(self.memberships.get(ws, [])):
if ws in self.rooms.get(room, set()):
self.rooms[room].remove(ws)
if not self.rooms[room]:
del self.rooms[room]
self.memberships.pop(ws, None)
async def main(host="0.0.0.0", port=8765):
server = ChatServer()
# Disable built-in pings so we can run our own heartbeat
async with websockets.serve(
server.handler,
host,
port,
ping_interval=None,
ping_timeout=None,
max_queue=32,
max_size=2**20,
):
print(f"Chat server running on ws://{host}:{port}")
await asyncio.Future() # run forever
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
How it works
- Protocol: Clients send JSON messages with an
action key. The server responds with JSON events indicating joins/leaves or errors. Broadcast messages are sent to all peers in the specified room.
- Room registry: The
ChatServer instance maintains rooms (a mapping of room name → set of websockets) and memberships (websocket → set of rooms). It cleans up on disconnect.
- Heartbeat: The
heartbeat coroutine sleeps for HEARTBEAT_INTERVAL seconds, then sends a ping. If a corresponding pong is not received within HEARTBEAT_TIMEOUT, the server closes the connection. Connections that close are removed from any rooms they were in.
Quick test with websocat
Install websocat and run two clients:
# Terminal 1
websocat -n ws://localhost:8765
{"action": "join", "room": "room1"}
{"action": "send", "room": "room1", "message": "Hello from client1"}
# Terminal 2
websocat -n ws://localhost:8765
{"action": "join", "room": "room1"}
Terminal 2 should receive the message broadcast by terminal 1. The server will close zombie connections that stop responding to pings.