DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • 8 Data Anonymization Techniques to Safeguard User PII Data
  • How to Optimize CPU Performance Through Isolation and System Tuning
  • Mainframe Development for the "No Mainframe" Generation
  • DevOps Midwest: A Community Event Full of DevSecOps Best Practices

Web Socket Demos with ColdFusion 10

Raymond Camden user avatar by
Raymond Camden
·
Feb. 24, 12 · Interview
Like (0)
Save
Tweet
Share
5.64K Views

Join the DZone community and get the full member experience.

Join For Free

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

Opinions expressed by DZone contributors are their own.

Trending

  • 8 Data Anonymization Techniques to Safeguard User PII Data
  • How to Optimize CPU Performance Through Isolation and System Tuning
  • Mainframe Development for the "No Mainframe" Generation
  • DevOps Midwest: A Community Event Full of DevSecOps Best Practices

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: