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:
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);
} }
component {
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.
Archived Comments
So on the shared whiteboard, if I have 2 tabs open on the whiteboard in chrome should they both be showing the same thing?
I only tested w/ two different browsers. Can you try that?
Shoot, it looks like the whiteboard one is broken. I'll add a note until I get a chance to fix it.
Whiteboard demo is fixed.
@Ray, still get an error on whiteboard.
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
@Salvatore IE doesn't support websockets ;) Maybe IE 10 will
@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.
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. :(
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
@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 :)
@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.
I must have uploaded the wrong file. It should be ok now.
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.
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.
Hey Ray, the demos are giving error messages, assuming is its because of changes in CF 10.
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.
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?
Nope, not yet, but if you are having issues you should *definitely* report it on the forums.
Ray - Is the demo still working?
I meant the chat demo : http://www.raymondcamden.co...
Nope.