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

PurposeEnable/disable WebSocket functionality
DefaultDisabled
RecommendationEnable if your application requires real-time communication
Note: After enabling, restart ColdFusion for changes to take effect. Verify firewall allows connections on configured port.

WebSocket Port

PurposePort for WebSocket connections
Default8575
RecommendationUse default unless conflict exists
Important: Ensure firewall and load balancer allow WebSocket traffic on this port. Update client connection URLs if you change the port.

Enable SSL

PurposeUse secure WebSocket connections (WSS)
DefaultDisabled
RecommendationAlways enable for production
Security: Always use WSS (secure WebSockets) in production to encrypt data transmission and prevent eavesdropping.

SSL Port

PurposePort for secure WebSocket connections
Default8576
RecommendationUse default unless conflict exists

Connection Settings

Maximum Connections

PurposeMaximum concurrent WebSocket connections
Default1000
RecommendationSet based on server capacity and expected load
Tuning: Monitor memory usage per connection. Each connection consumes memory. For high-traffic applications, consider clustering and load balancing.

Connection Timeout (seconds)

PurposeTime to keep idle connections alive
Default1800 (30 minutes)
Recommendation15-30 minutes for most applications
Best Practice: Implement heartbeat/ping-pong messages to keep active connections alive. Close inactive connections to free resources.

Message Size Limit (KB)

PurposeMaximum size of individual messages
Default1024 (1MB)
RecommendationKeep messages small (under 100KB) for best performance
Performance: Large messages increase memory usage and latency. For large data, consider pagination or chunking.

Buffer Size (KB)

PurposeSend/receive buffer size per connection
Default64
RecommendationUse default unless high-frequency messaging requires larger buffers

SSL/TLS Settings

Keystore Path

PurposePath to SSL certificate keystore
RequirementRequired for SSL
Example/opt/coldfusion/certs/keystore.jks
Setup: Use Java keytool to create keystore. Ensure ColdFusion has read permissions on the keystore file.

Keystore Password

PurposePassword for keystore access
RequirementRequired for SSL
Security: Use a strong password and store securely. Do not commit passwords to version control.

Key Password

PurposePassword for private key
RequirementOptional (if different from keystore password)

SSL Protocol

PurposeTLS version (TLS 1.2, TLS 1.3)
RequirementTLS 1.2+
RecommendationUse TLS 1.3 for best security
Security: TLS 1.0 and 1.1 are deprecated. Only use TLS 1.2 or higher.

Using WebSockets in CFML

Server-Side WebSocket Channel

Create a WebSocket channel handler:

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:

WebSocket Client Connection
// 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:

Publishing to WebSocket Channels
// 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:

Managing WebSocket 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

Related Resources