lid

WebSocket in ColdFusion

ColdFusion 10 provides a new and awesome feature called cfwebsocket, a bi-directional communication channel. This post describes the use of websockets in ColdFusion.


What is Websocket?

WebSocket is a protocol providing bi-directional(full-duplex) communication between multiple clients and server. Once a WebSocket connection is established, the client or server can send a message at any time to the each other. This connection persists until the client or server decides to close.

Before WebSocket, all communication between the browsers and servers relied only on HTTP. Now, websocket's open connection allows dynamic data to flow freely between the network without requesting the server frequently.


CFwebsocket

The release of CF10 provides the support for websocket connection in ColdFusion applications. ColdFusion provides a messaging layer for the WebSocket protocol, which we can control using CFML and JavaScript.

We can achieve Websocket connection in ColdFusion applications through <cfwebsocket> tag, which creates a javascript reference object for WebSockets in CFM template.


Let us provide an example of how the websockets work on ColdFusion. So consider a simple polling application, which pupil polls for a candidate and the vote count of candidate increased simultaneously.

  1. First let us define our websocket Channel in Application.cfc. A websocket channel is the communication path where message flow freely between the connected terminals.
  2. this.wschannels = [{name="poll"}];
  3. So a WS channel has been defined and we can pass a message or data to the channel.

    Here we're voting for a candidate, and it has been published to the "Poll" Channel using the built-in ColdFusion method called WsPublish(), it publishes the data to the specified channel.

  4. Next we need to get message/data from the corresponding Channel and display it to the client. For that we need to subscribe to that WS Channel and create a Javascript object, to get server updates from the Channel and render it in the client(browser).

    So from the above code we've created a Javascript object called "PollingConnection" and subscribed to the "poll" Channel using the Cfwebsocket tag. Also calling the user defined javascript method called PollMessageHandler(), while the Poll Channel receives any message from the server.

    The PollMessageHandler() will listen to the Poll Channel for messages, if any available, it'll render it to the client. From our example, the PollMessageHandler() will get the candidate vote from the channel, add it to his/her vote count and display it in the client.

You can get the Live Demo Here

And unfortunately We don't have the support to implement Websockets functionality in Lucee 4.5. So we need to find an extension provider for Websockets in Lucee. Let us discuss about that in our future blog post




lid