Example: Chat¶
A multi-user chat room powered entirely by Pyplet. Messages arrive over WebSockets, the UI updates through Pyodide DOM calls, and no JavaScript is required.
Location¶
- Repository:
https://github.com/cetic/pyplet_examples - Path:
apps/pyplet_examples/examples/chat_* - Client entry point:
chat_client.py - Server loop:
chat_server.py
Fetch or refresh the examples submodule:
Highlights¶
chat_client.py:26unwraps the handshake payload to display the assigned username.
async def websocket_client_loop(ws: pyplet.WebSocket):
init = decode(await ws.receive())
assert init["type"] == "init"
render(f"<b>Logged in as {init['name']}</b>")
chat_client.py:31usespyodide.create_proxyto wire DOM events directly to the WebSocket.
@create_proxy
async def submit(_):
message = input.value
input.value = ""
await ws.send(message)
input.addEventListener("change", submit)
chat_server.py:35rebroadcasts every message to all connected clients.
while True:
msg = await ws.receive()
if msg is ws.closing_message:
break
msg = json.dumps({"type": "message", "name": name, "message": msg})
await asyncio.gather(*(s.send(msg) for s in sockets.values()))
chat_server.py:42manages the user pool, removing sockets when clients disconnect.
This example demonstrates two-way real-time messaging with minimal boilerplate—ideal for exploring Pyplet’s WebSocket helpers.