Server Settings - WebSocket
Configure WebSocket server settings
Overview
The WebSocket Settings page configures ColdFusion's WebSocket server for real-time, bidirectional communication between the server and browser clients. WebSockets enable push notifications, live chat applications, real-time dashboards, collaborative editing, and other interactive features that require instant data updates without polling.
ColdFusion's WebSocket implementation provides a high-performance, scalable solution for real-time communication with built-in support for channels, message broadcasting, authentication, and SSL/TLS encryption.
WebSocket Configuration Settings
Configure server status, connection limits, and security settings for WebSocket communication.
Server Status
Enable WebSocket Server
WebSocket Port
Enable SSL
SSL Port
Connection Settings
Maximum Connections
Connection Timeout (seconds)
Message Size Limit (KB)
Buffer Size (KB)
SSL/TLS Settings
Keystore Path
/opt/coldfusion/certs/keystore.jksKeystore Password
Key Password
SSL Protocol
Using WebSockets in CFML
Server-Side WebSocket Channel
Create a WebSocket channel handler:
component {
function onOpen(required struct token) {
wsPublish("myChannel", "User connected: #token.connectionID#");
}
function onMessage(required struct message) {
wsPublish("myChannel", message.data);
}
function onClose(required struct token) {
wsPublish("myChannel", "User disconnected");
}
}<cfcomponent>
<cffunction name="onOpen" returntype="void">
<cfargument name="token" type="struct">
<cfset wsPublish("myChannel", "User connected: #token.connectionID#")>
</cffunction>
<cffunction name="onMessage" returntype="void">
<cfargument name="message" type="struct">
<cfset wsPublish("myChannel", message.data)>
</cffunction>
<cffunction name="onClose" returntype="void">
<cfargument name="token" type="struct">
<cfset wsPublish("myChannel", "User disconnected")>
</cffunction>
</cfcomponent>Client-Side JavaScript
Connect to WebSocket from browser:
// Create WebSocket connection
var ws = new WebSocket("ws://localhost:8575/cfusion/ws/myChannel");
// Connection opened
ws.onopen = function(event) {
console.log("Connected to WebSocket");
ws.send("Hello Server!");
};
// Receive messages
ws.onmessage = function(event) {
console.log("Received:", event.data);
// Update UI with received data
};
// Handle errors
ws.onerror = function(error) {
console.error("WebSocket error:", error);
};
// Connection closed
ws.onclose = function(event) {
console.log("Disconnected from WebSocket");
};Publishing Messages
Send messages to connected clients:
// Publish to all subscribers
wsPublish("myChannel", {
type: "notification",
message: "Server update",
timestamp: now()
});
// Publish to specific subscriber
wsPublish("myChannel", messageData, subscriberID);
// Broadcast to all channels
wsBroadcast({alert: "System maintenance in 10 minutes"});<!--- Publish to all subscribers --->
<cfset wsPublish("myChannel", {
type: "notification",
message: "Server update",
timestamp: now()
})>
<!--- Publish to specific subscriber --->
<cfset wsPublish("myChannel", messageData, subscriberID)>
<!--- Broadcast to all channels --->
<cfset wsBroadcast({alert: "System maintenance in 10 minutes"})>Managing Connections
Get information about active connections:
// Get all subscribers to a channel
subscribers = wsGetSubscribers("myChannel");
// Get all active channels
channels = wsGetAllChannels();
// Close a specific connection
wsCloseConnection(connectionID);<!--- Get all subscribers to a channel --->
<cfset subscribers = wsGetSubscribers("myChannel")>
<!--- Get all active channels --->
<cfset channels = wsGetAllChannels()>
<!--- Close a specific connection --->
<cfset wsCloseConnection(connectionID)>WebSocket Use Cases
Real-Time Notifications
- Push notifications to users instantly
- Alert users of system events or updates
- Notify users of new messages or activities
- Display real-time status updates
Live Chat Applications
- Instant messaging between users
- Customer support chat systems
- Group chat rooms and channels
- Typing indicators and presence detection
Real-Time Dashboards
- Live data visualization and charts
- System monitoring dashboards
- Stock tickers and financial data
- Social media feeds and analytics
Collaborative Applications
- Collaborative document editing
- Shared whiteboards and drawing tools
- Multi-user project management
- Real-time form collaboration
Gaming and Interactive Apps
- Multiplayer game synchronization
- Real-time scoring and leaderboards
- Live polling and voting
- Interactive quizzes and competitions
Best Practices
Production Configuration
- Enable SSL/TLS for WebSocket connections in production
- Use secure (WSS) protocol for sensitive data transmission
- Configure appropriate connection limits based on server capacity
- Set reasonable timeout values to free up idle connections
- Monitor WebSocket server resource usage
- Implement connection authentication and authorization
Security
- Always use WSS (secure WebSockets) in production
- Implement authentication before allowing channel subscriptions
- Validate and sanitize all incoming messages
- Use channel-level access control
- Rate limit message sending to prevent abuse
- Log suspicious connection patterns
- Implement CSRF protection for WebSocket handshake
Performance
- Keep messages small and efficient
- Use JSON for structured data transmission
- Implement message batching for high-frequency updates
- Close unused connections promptly
- Monitor memory usage per connection
- Consider horizontal scaling for high traffic
Error Handling
- Implement automatic reconnection logic in clients
- Handle connection failures gracefully
- Provide fallback mechanisms (long polling, SSE)
- Log connection errors for debugging
- Display user-friendly connection status indicators
- Queue messages during temporary disconnections
Troubleshooting
WebSocket Server Won't Start
If the WebSocket server fails to start:
- Verify WebSocket is enabled in administrator
- Check configured port is not already in use
- Ensure firewall allows connections on WebSocket port
- Verify SSL keystore configuration if SSL is enabled
- Review coldfusion-out.log for startup errors
- Check file permissions on keystore file
Clients Cannot Connect
If clients fail to establish WebSocket connections:
- Verify WebSocket URL format (ws:// or wss://)
- Check correct hostname and port are specified
- Ensure firewall/load balancer allows WebSocket traffic
- Verify proxy servers support WebSocket protocol
- Check browser console for connection errors
- Test with simple WebSocket client tool
Connections Dropping Frequently
If WebSocket connections disconnect often:
- Increase connection timeout setting
- Implement heartbeat/ping-pong messages
- Check network stability and latency
- Verify proxy/load balancer timeout settings
- Review server resource usage (CPU, memory)
- Check for application errors closing connections
Messages Not Being Received
If messages aren't reaching clients:
- Verify channel names match exactly (case-sensitive)
- Check client is subscribed to correct channel
- Confirm connection is still active
- Review message size against configured limits
- Check for JavaScript errors in client code
- Test with simpler message formats
High Memory Usage
If WebSocket server uses excessive memory:
- Reduce maximum connection limit
- Decrease message buffer sizes
- Implement connection cleanup for idle clients
- Review application for memory leaks
- Monitor number of active channels and subscribers
- Close unused connections programmatically
SSL/TLS Connection Failures
If secure WebSocket connections fail:
- Verify SSL certificate is valid and not expired
- Check keystore path and password are correct
- Ensure certificate matches server hostname
- Verify TLS version compatibility
- Check for certificate chain issues
- Test with self-signed certificate first
Advanced Configuration
Load Balancing WebSockets
Scaling WebSocket connections across multiple servers:
- Configure sticky sessions on load balancer
- Use Redis or other message broker for cross-server messaging
- Implement session affinity based on connection ID
- Monitor connection distribution across servers
- Plan for graceful server shutdowns
Monitoring and Metrics
- Track active connection count
- Monitor message throughput (sent/received per second)
- Measure average connection duration
- Log connection failures and errors
- Alert on connection limit thresholds
- Track memory and CPU usage per connection
Authentication and Authorization
- Implement token-based authentication
- Validate user credentials before channel subscription
- Use session management for connection tracking
- Implement channel-level permissions
- Support OAuth or JWT for authentication
- Log authentication attempts and failures
Performance Tuning
Connection Limits
Recommended connection limits based on application scale and traffic patterns.
Low Traffic
- Recommended Limit
- 100-500 connections
- Use Case
- Small applications with limited concurrent users
Suitable for internal tools, small team applications, and low-volume services.
Medium Traffic
- Recommended Limit
- 500-2000 connections
- Use Case
- Moderate user base with typical usage patterns
Standard configuration for most production applications with regular user activity.
High Traffic
- Recommended Limit
- 2000-5000 connections
- Use Case
- Large user base with high concurrent activity
Requires careful resource planning and monitoring. Consider vertical scaling.
Enterprise
- Recommended Limit
- 5000+ connections
- Use Case
- Massive scale with thousands of concurrent users
Requires clustering, load balancing, and horizontal scaling architecture.
Message Optimization
- Use compact JSON format for messages
- Implement message compression for large payloads
- Batch multiple updates into single messages
- Use binary format for non-text data
- Implement delta updates instead of full objects