The WebSocket Server provides real-time communication for ChessClouds, handling game sessions and move synchronization between players.
- Real-time bidirectional communication
- Game state management
- Reconnection support
- Move validation
- Game outcome determination
- Game persistence
The WebSocket server is built in Rust using:
- Axum web framework
- Tokio asynchronous runtime
- SQLx
- Shakmaty for Chess rule implementation and move validation
- SCC for concurrent HashMap
The WebSocket server uses a message-based protocol for communication:
type ClientMessage =
| { kind: "Auth"; value: { game_id: string; user_id: string } }
| { kind: "Move"; value: string }
| { kind: "Ping" };type ServerMessage =
| { kind: "Move"; value: string }
| { kind: "GameEnd"; value: Outcome }
| { kind: "Error"; value: Error }
| { kind: "AuthSuccess" }
| { kind: "MoveHistory"; value: Array<string> }
| { kind: "Pong" };- Connection - Client connects to WebSocket endpoint
- Authentication - Client sends Auth message with game_id and user_id
- Game State - Server responds with move history for the game (for reconnection)
- Gameplay - Clients exchange moves through the server
- Game End - Server detects end of game and broadcasts result
- Disconnection - Server handles graceful disconnections and reconnections
- Rust
- PostgreSQL database
-
Create an
.envfile with aDATABASE_URLvariable. -
Run the server
cargo rundocker build -t chessclouds-ws-server .
docker run -p 8000:8000 -e DATABASE_URL=postgres://user:password@host/db chessclouds-ws-serverThe server interacts with the gamestate table:
CREATE TABLE gamestate (
gameid UUID PRIMARY KEY,
white TEXT NOT NULL,
black TEXT NOT NULL,
pgn TEXT NOT NULL,
createdat TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status "GameStatus" NOT NULL DEFAULT 'On Going'
);The project includes test clients for simulating various game scenarios:
# Run a test game ending in checkmate with two players
cargo run --bin client
# Test client disconnection handling
cargo run --bin client_disconnect
# Run test suite
cargo run --bin test