Technology
This module provides a comprehensive WebSocket service for Project Forge applications, enabling real-time bidirectional communication between clients and the server.
Features
- Connection Management: Automatic connection registration, heartbeat, and cleanup
- Channel System: Multi-channel communication with join/leave functionality
- Message Routing: Type-safe message handling with custom commands
- User Integration: Seamless integration with user authentication and profiles
- Admin Interface: Built-in WebSocket status and debugging tools
- TypeScript Client: Full-featured client with automatic reconnection
- Broadcasting: Send messages to channels, users, or all connections
Architecture
Core Components
- Service: Central WebSocket service managing connections and channels
- Connection: Individual WebSocket connection with user context
- Channel: Named communication channels for grouping connections
- Message: Structured message format with commands and parameters
- Handler: Custom message processing logic
Usage
1. Backend Setup
Create Controller Handlers
1 | |
Implement Message Handler
1 | |
Register Routes
1 | |
2. Frontend Setup
TypeScript Client
1 | |
HTML Template Integration
1 | |
Service API
Core Methods
1 | |
Status and Monitoring
1 | |
Admin Interface
The module includes built-in admin pages accessible at:
/admin/websocket- WebSocket service status and active connections- Real-time connection monitoring
- Channel membership display
- Message broadcasting tools
Best Practices
- Error Handling: Always handle WebSocket errors gracefully with reconnection logic
- Message Validation: Validate all incoming message parameters
- Rate Limiting: Implement rate limiting for message-heavy applications
- Channel Management: Use meaningful channel names and clean up unused channels
- Security: Validate user permissions before joining channels or processing commands
- Performance: Avoid blocking operations in message handlers
Common Patterns
Chat Application
- Use channels for chat rooms
- Broadcast messages to channel members
- Handle user join/leave events
Real-time Updates
- Subscribe clients to data channels
- Push updates when server data changes
- Use different message types for different data
Gaming/Collaboration
- Use per-game/session channels
- Implement custom game logic in handlers
- Synchronize state between clients
Notifications
- Global notification channel for all users
- User-specific channels for private notifications
- Different message types for different notification levels
Source Code
- Repository: https://github.com/kyleu/projectforge/tree/main/module/websocket
- License: CC0 (Public Domain)
- Author: Kyle U (kyle@kyleu.com)