# WebSocket Integration Testing Guide This guide walks you through testing the WebSocket event system for game notifications. ## Prerequisites 1. Backend API running with WebSocket support 2. Valid JWT token for authentication 3. Active session with games (or ability to create one) ## Testing Steps ### Step 1: Install Backend Dependencies ```bash cd backend npm install ``` This will install the `ws` package that was added to `package.json`. ### Step 2: Start the Backend ```bash cd backend npm start ``` You should see: ``` Server is running on port 5000 WebSocket server available at ws://localhost:5000/api/sessions/live [WebSocket] WebSocket server initialized on /api/sessions/live ``` ### Step 3: Get JWT Token ```bash curl -X POST "http://localhost:5000/api/auth/login" \ -H "Content-Type: application/json" \ -d '{"key":"YOUR_ADMIN_KEY"}' ``` Save the token from the response. ### Step 4: Test WebSocket Connection Run the test script: ```bash cd backend JWT_TOKEN="your_token_here" node test-websocket.js ``` Expected output: ``` 🚀 WebSocket Test Client ═══════════════════════════════════════════════════════ Connecting to: ws://localhost:5000/api/sessions/live ✅ Connected to WebSocket server 📝 Step 1: Authenticating... ✅ Authentication successful 📝 Step 2: Subscribing to session 1... ✅ Subscribed to session 1 🎧 Listening for events... Add a game in the Picker page to see events here Press Ctrl+C to exit ``` ### Step 5: Test Game Added Event 1. Keep the WebSocket test client running 2. Open the web app in your browser 3. Go to the Picker page 4. Add a game to the session You should see in the test client: ``` 🎮 GAME ADDED EVENT RECEIVED! ═══════════════════════════════════════════════════════ Game: Fibbage 4 Pack: The Jackbox Party Pack 9 Players: 2-8 Session ID: 1 Games Played: 1 Timestamp: 2025-11-01T... ═══════════════════════════════════════════════════════ ``` ### Step 6: Test Bot Integration If you're using the `irc-kosmi-relay` bot: 1. Make sure `UseWebSocket=true` in `matterbridge.toml` 2. Build and run the bot: ```bash cd irc-kosmi-relay go build ./matterbridge -conf matterbridge.toml ``` 3. Look for these log messages: ``` INFO Jackbox integration initialized successfully INFO Connecting to WebSocket: wss://your-api-url/api/sessions/live INFO WebSocket connected INFO Authentication successful INFO Subscribed to session X ``` 4. Add a game in the Picker page 5. The bot should announce in Kosmi/IRC: ``` 🎮 Coming up next: Fibbage 4! ``` ## Troubleshooting ### Connection Refused **Problem**: `Error: connect ECONNREFUSED` **Solution**: Make sure the backend is running on the correct port (default 5000). ### Authentication Failed **Problem**: `Authentication failed: Invalid or expired token` **Solution**: - Get a fresh JWT token - Make sure you're using the correct admin key - Check token hasn't expired (tokens expire after 24 hours) ### No Events Received **Problem**: WebSocket connects but no `game.added` events are received **Solution**: - Make sure you're subscribed to the correct session ID - Verify the session is active - Check backend logs for errors - Try adding a game manually via the Picker page ### Bot Not Connecting **Problem**: Bot fails to connect to WebSocket **Solution**: - Check `APIURL` in `matterbridge.toml` is correct - Verify `UseWebSocket=true` is set - Check bot has valid JWT token (authentication succeeded) - Look for error messages in bot logs ### Reconnection Issues **Problem**: WebSocket disconnects and doesn't reconnect **Solution**: - Check network connectivity - Backend automatically handles reconnection with exponential backoff - Bot automatically reconnects on disconnect - Check logs for reconnection attempts ## Advanced Testing ### Test Multiple Clients You can run multiple test clients simultaneously: ```bash # Terminal 1 JWT_TOKEN="token1" node test-websocket.js # Terminal 2 JWT_TOKEN="token2" node test-websocket.js ``` Both should receive the same `game.added` events. ### Test Heartbeat The WebSocket connection sends ping/pong messages every 30 seconds. You should see: ``` 💓 Heartbeat ``` If you don't see heartbeats, the connection may be stale. ### Test Reconnection 1. Start the test client 2. Stop the backend (Ctrl+C) 3. The client should log: `WebSocket disconnected, reconnecting...` 4. Restart the backend 5. The client should reconnect automatically ## Integration Checklist - [ ] Backend WebSocket server starts successfully - [ ] Test client can connect and authenticate - [ ] Test client receives `game.added` events - [ ] Heartbeat keeps connection alive (30s interval) - [ ] Auto-reconnect works after disconnect - [ ] Multiple clients can connect simultaneously - [ ] Invalid JWT is rejected properly - [ ] Bot connects and authenticates - [ ] Bot receives events and broadcasts to chat - [ ] Bot reconnects after network issues ## Next Steps Once testing is complete: 1. Update your bot configuration to use `UseWebSocket=true` 2. Deploy the updated backend with WebSocket support 3. Restart your bot to connect via WebSocket 4. Monitor logs for any connection issues 5. Webhooks remain available as a fallback option ## Comparison: WebSocket vs Webhooks | Feature | WebSocket | Webhooks | |---------|-----------|----------| | Setup Complexity | Simple | Moderate | | Inbound Ports | Not needed | Required | | Docker Networking | Simple | Complex | | Latency | Lower | Higher | | Connection Type | Persistent | Per-event | | Reconnection | Automatic | N/A | | Best For | Real-time bots | Serverless integrations | **Recommendation**: Use WebSocket for bot integrations. Use webhooks for serverless/stateless integrations or when WebSocket is not feasible.