Simple barebones CF10/CF11 WebSocket Example

Here’s a bare-bones example of setting up an HTML5 WebSockets chat service using ColdFusion 10/11:

<!--- application.cfc --->
<cfcomponent>
  <cfset this.name = "Cf11Examples">
  <cfset this.wschannels = [{name="chat"}]>
</cfcomponent>
<!--- index.cfm --->
<cfwebsocket name="webSocketObj"
             onMessage="messageHandler"
             onError="errorHandler"
             onOpen="openHandler"
             onClose="closeHandler"
             subscribeTo="chat"/>
             
<doctype html>
<head>
	<title>WebSocket Example</title>
	<script type="text/javascript">
		
		messageHandler =  function(aEvent,aToken) {
		 
		  if (aEvent.data) {
           var txt=document.getElementById("msgArea"); 
           txt.innerHTML += aEvent.data  +"<br />"; 
          }
		}
		
		openHandler = function() {
			alert("Connection is open");
		}
		
		closeHandler= function() {
			alert("Connection Closed");
		}
		
		errorHandler = function() {
			alert("Doh!");
			console.log(arguments);
		}
		
		sendMessage = function() {
			var text = window.prompt("Enter some text","");
			if (text) {
				webSocketObj.publish("chat", text);
			}
		}
	</script>
</head>
<body>
 	<div id="msgArea" />
 	<input type="button" value="Send Message" onClick="sendMessage()">
</body>
</html>

One thought on “Simple barebones CF10/CF11 WebSocket Example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s