HTML5 Zone is brought to you in partnership with:

Raymond Camden is a developer evangelist for Adobe. His work focuses on web standards, mobile development and Cold Fusion. He's a published author and presents at conferences and user groups on a variety of topics. He is the happily married proud father of three kids and is somewhat of a Star Wars nut. Raymond can be reached via his blog at www.raymondcamden.com or via email at raymondcamden@gmail.com Raymond is a DZone MVB and is not an employee of DZone and has posted 213 posts at DZone. You can read more from them at their website. View Full User Profile

Web Socket Demos with ColdFusion 10

02.24.2012
| 3703 views |
  • submit to reddit

One of my favorite new features in ColdFusion 10 is the powerful web socket support. If you've never looked at web sockets before, you can check out the Wikipedia entry. Simply put, it is a simple way to create a two way connection between multiple clients (browsers) and your server. Like most things, ColdFusion makes using web sockets incredibly easy. Let's look at a few demos.

First, consider a simple chat application. I hate chat app examples, but while I was learning this feature myself I figured it was the easiest app I could build.

I began by defining my web socket in my Application.cfc file:

this.wschannels = [
    {name="chat"}
];

To use a web socket and a corresponding JavaScript object, my template began with this line:

<cfwebsocket name="chatWS" subscribeTo="chat"
             onMessage="msgHandler">

And that's it. Really. Obviously this is a simple case though. Creating a web socket is a bit like creating a cable network. Your application can support any number of channels. This allows you to send different information for different purposes. Since our chat app is trivial, we can create and subscribe to a channel all via the ColdFusion tag. In more complex applications, you would create the socket and subscribe to channels dynamically.

Sending a message is possible via the JavaScript object we create in the cfwebsocket tag:

msg = {
    type: "chat",
    username: username,
    chat: txt
};
chatWS.publish("chat",msg);

Messages are ad hoc objects that you can create as you see fit. There are no required values at all. On the flip side, you can use a message handler to display the messages received from the web socket.

function msgHandler(message){
    //Only care about messages
    if (message.type == "data") {
        var data = JSON.parse(message.data);
        if(data.type == "chat") $("#chatlog").append(data.username + " says: " + data.chat + "\n");
        else $("#chatlog").append(data.chat + "\r");
        $('#chatlog').scrollTop($('#chatlog')[0].scrollHeight);
        console.log("Append "+data.chat);
    }
}

You can see this demo here: http://www.raymondcamden.com/demos/2012/feb/19/chat/. I'm not going to paste the entire code template in since outside of the one ColdFusion tag, the rest is all client-side code. I encourage you to view source to see the complete template.

How about a slightly more useful example? I built a simple chart demo. It uses jQuery to send your votes (and yes, you can vote more than once) to a CFC....

function voteYes() {
    $.get("vote.cfc?method=savevote", {"key":"yes"}, function() {});
    console.log("Yes");
}    
function voteNo() {
    $.get("vote.cfc?method=savevote", {"key":"no"}, function() {});
    console.log("No");
}

And then the server side CFC publishes new chart data to the clients:

component {

    remote void function savevote(key) {
        //Note, should probably lock this
        if(key == "yes") application.votes.yes++;
        else if(key == "no") application.votes.no++;
        else abort;
        
        msg = {"votes":application.votes};
        wspublish("vote",msg);
    }

}

This example could be redone so that the web socket itself - using a CFC handler - takes care of updating chart data, but at the time of me writing it I wasn't quite sure how to do that.

For a third demo, I built a simple shared whiteboard. It uses canvas to draw and "broadcast" lines to all the clients. So for example, here's how we handle drawing/broadcasting:

$(document).ready(function() {
    var whiteboard = $("#whiteboard");
    canvas = whiteboard[0].getContext("2d");
    var offset = whiteboard.offset();    

    whiteboard.bind("mousedown", function(e) {
        canvas.beginPath();
        pointX = e.clientX-offset.left;
        pointY = e.clientY-offset.top;
        canvas.arc(pointX,pointY, 2, 0, Math.PI*2,false);
        canvas.strokeStyle = "#000";
        canvas.stroke();
        if(oldX && oldY) {
            canvas.lineTo(oldX,oldY);
            canvas.stroke();
            whiteboardWS.publish("whiteboard", {type:"draw",origin:userid, from:{x:pointX,y:pointY},to:{x:oldX,y:oldY}});
        }
        oldX=pointX, oldY=pointY;
    });

})

And here's my listener to draw lines from other clients:

function msgHandler(message){
    //notice welcome
    if (message.type == "response" && !userid) {
        userid = message.utid;    
    }
    if (message.type == "data") {
        var data = JSON.parse(message.data);
        //console.dir(m);
        if(data.origin == userid) return;
        console.dir(data);
        canvas.beginPath();
        canvas.moveTo(data.from.x, data.from.y);
        canvas.lineTo(data.to.x,data.to.y);
        canvas.stroke();
        canvas.closePath();
    }
} 

You can play with this one here: http://www.raymondcamden.com/demos/2012/feb/19/whiteboard/.

For the full source of these demos, grab the download from my demo dump of a few days ago.

 

Source: http://www.raymondcamden.com/index.cfm/2012/2/20/ColdFusion-10-Web-Socket-Demos

Published at DZone with permission of Raymond Camden, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)