A multi-room chat server. Browsers and command-line clients connect over
WebSocket at /ws/; a single chat server task routes messages between them.
Things to look at:
src/main.rsupgradesGET /ws/withws::start()and runs one session per connection. A heartbeat task pings every 5 seconds and drops clients that stay silent for 10 seconds.src/server.rsis the chat server: a task that owns the room list and talks to the sessions overfutureschannels.- The chat server handle reaches the handlers through application state
(
ChatState,build_with(),to_with_state()).
For a version that also accepts raw TCP clients, see
tcp-chat.
cd websockets/chat
cargo run --bin websocket-chat-serverThe server listens on 127.0.0.1:8080. Run it from websockets/chat so the
static files in static/ are found.
Browser: open http://localhost:8080/, which redirects to
/static/websocket.html. Open it in several tabs to chat with yourself.
Python: requires aiohttp:
pip install aiohttp
python client.py # --host and --port default to 127.0.0.1:8080Every new session joins the Main room. Lines that start with / are
commands; anything else is sent to everyone else in your current room.
| Command | Effect |
|---|---|
/list |
List the available rooms |
/join <room> |
Join a room, creating it if needed |
/name <name> |
Set the name shown before your messages |
| any other text | Send a message to the current room |
- Servers with
web::wsand heartbeats and closing in the WebSocket chapter of the ntex guide. - Application state.
cargo test -p websocket-chatThe tests connect two clients to the real chat server and cover room broadcasts, ping/pong, and a missing room argument.