ColdFusion 10 Web Socket Demos

This post is more than 2 years old.

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.

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by me posted on 2/20/2012 at 10:18 PM

So on the shared whiteboard, if I have 2 tabs open on the whiteboard in chrome should they both be showing the same thing?

Comment 2 by Raymond Camden posted on 2/21/2012 at 12:20 AM

I only tested w/ two different browsers. Can you try that?

Comment 3 by Raymond Camden posted on 2/21/2012 at 12:21 AM

Shoot, it looks like the whiteboard one is broken. I'll add a note until I get a chance to fix it.

Comment 4 by Raymond Camden posted on 2/21/2012 at 10:51 AM

Whiteboard demo is fixed.

Comment 5 by Patrick Heppler posted on 2/21/2012 at 4:00 PM

@Ray, still get an error on whiteboard.

Comment 6 by Salvatore Fusto posted on 2/21/2012 at 4:00 PM

Ray,
your demo is ok on chrome and ff, but not on ie 8: on ie i can't see neither the logging message, nor any post.
Bye

Comment 7 by Patrick Heppler posted on 2/21/2012 at 5:11 PM

@Salvatore IE doesn't support websockets ;) Maybe IE 10 will

Comment 8 by Raymond Camden posted on 2/21/2012 at 5:32 PM

@Patrick: What error? Previously the whiteboard demo just didn't work, but no errors were throw.

@Sal: Our websocket support has fallback for Flash. We also added, but I didn't use, support for 'no web socket, no Flash, say something at least', so in theory, I should have been able to do something for you. Also, if you used the whiteboard demo, it's Canvas, so it definitely won't work in IE8.

Comment 9 by Jack Poe posted on 2/21/2012 at 6:31 PM

I don’t see live data pushes in Firefox 10 either. The chat window doesn’t show anything and the I had to reload the chart to see the posted data. :(

Comment 10 by Salvatore Fusto posted on 2/21/2012 at 7:16 PM

Ray, esxcuse me.
i was referring to the chat example: it works fine in chrome and ff, not in ie, as i don't see posts from others, nor it echoes the login message.
i'm test using the 3 browsers myself on my pc.
regards

Comment 11 by Patrick Heppler posted on 2/21/2012 at 11:46 PM

@Ray I just hit the whiteboard again and I still get a coldfusion error:
Attribute validation error for the CFWEBSOCKET tag
The channel entry specified for subscribeTo is not valid. vote is not a valid channel

@Salvatore as said, IE doesn't support web sockets, so none of the demos would work in IE. IE is crap and always will be, IMFAO :)

Comment 12 by Raymond Camden posted on 2/22/2012 at 9:29 AM

@Jack: I tested in FF10 as well, and it works ok. Maybe it's a firewall issue on your network blocking the web socket port?

@Sal: Can you also test your network to ensure 8080 isn't blocked?

@Patrick: Woah, yeah, that wasn't there before. Taking a look see.

Comment 13 by Raymond Camden posted on 2/22/2012 at 9:31 AM

I must have uploaded the wrong file. It should be ok now.

Comment 14 by Gary F posted on 2/23/2012 at 8:08 PM

Isn't Flash fallback support supposed to be automatic?

BTW, the chart demo shows a very grey chart in FF, not the nice blue chart that IE9 and Chrome show. Is there a problem with rendering charts in FF (10.02 in Windows)?

Very good demos by the way, Ray. I was hoping someone would publish some simple examples as this is all new stuff.

Comment 15 by Raymond Camden posted on 2/24/2012 at 4:46 PM

Yes, it should be.

grey chart: Gary, please file a bug report for this. I've seen this in the past but I've never been able to reproduce it well on demand.

Comment 16 by Matthew posted on 2/28/2012 at 9:00 AM

Hey Ray, the demos are giving error messages, assuming is its because of changes in CF 10.

Comment 17 by Raymond Camden posted on 2/28/2012 at 9:06 AM

Actually no - they only work in CF10. I had to revert my server which means my demos no longer work. As soon as I can, I'll return this box to CF10.

Comment 18 by Sean Ford posted on 4/2/2014 at 10:22 AM

I'm curious if you've tested CFwebsocket on CF11 yet? It does not work for me as the Javascript is never inserted into the page?

Comment 19 by Raymond Camden posted on 4/2/2014 at 3:16 PM

Nope, not yet, but if you are having issues you should *definitely* report it on the forums.

Comment 20 by John posted on 9/4/2014 at 7:33 PM

Ray - Is the demo still working?

Comment 21 by John posted on 9/4/2014 at 7:36 PM

I meant the chat demo : http://www.raymondcamden.co...

Comment 22 by Raymond Camden posted on 9/4/2014 at 7:36 PM

Nope.