Implement WebSocket real-time communication for game
Replace HTTP API with WebSocket for true real-time bidirectional communication:
Backend Changes:
- Add Ratchet WebSocket library (cboden/ratchet) to composer.json
- New GameWebSocketServer class implementing MessageComponentInterface
- Handles client connections and session management
- Message types: login, game-input, sync-state, ping/pong
- Maintains client connections map and user sessions
- New websocket-server.php startup script
- Listens on port 9001
- Uses Ratchet with HttpServer wrapper
Frontend Changes:
- New game-ws.html with WebSocket implementation
- Replace HTTP requests with WebSocket messages
- Keep HTTP for authentication (login/register/status)
- WebSocket handles all game interactions
- Real-time status display with connection indicator
- Implements reconnection on disconnect
- 30-second heartbeat (ping/pong) to maintain connection
Message Protocol:
Client → Server:
login: { userId, username } - Authenticate and load game
game-input: { input } - Send game command
sync-state: {} - Request full state sync
ping - Heart beat
Server → Client:
welcome - Initial greeting
login-success - Auth successful, game loaded
game-output - Normal command output
battle-start/end - Battle state changes
state-sync - Full state snapshot
error - Error message
pong - Heartbeat response
Port Configuration:
- HTTP API: port 80 (web server)
- WebSocket: port 9001 (Ratchet server)
- Both services run independently
Usage:
1. Start web server: php -S 0.0.0.0:8080 web/server.php
2. Start WebSocket server: php websocket-server.php
3. Open browser: http://localhost:8080/game-ws.html
Benefits:
✓ True bidirectional real-time communication
✓ Can handle battle interactions in-game
✓ Better for multiplayer scenarios
✓ Persistent connections reduce latency
✓ Future support for spectating, PvP
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>