Posted in Development, jQuery, JavaScript, HTML5, ColdFusion | Posted on 02-20-2012 | 2,722 views
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:
2 {name="chat"}
3];
To use a web socket and a corresponding JavaScript object, my template began with this line:
2 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:
2 type: "chat",
3 username: username,
4 chat: txt
5};
6chatWS.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.
2 //Only care about messages
3 if (message.type == "data") {
4 var data = JSON.parse(message.data);
5 if(data.type == "chat") $("#chatlog").append(data.username + " says: " + data.chat + "\n");
6 else $("#chatlog").append(data.chat + "\r");
7 $('#chatlog').scrollTop($('#chatlog')[0].scrollHeight);
8 console.log("Append "+data.chat);
9 }
10}
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....
2 $.get("vote.cfc?method=savevote", {"key":"yes"}, function() {});
3 console.log("Yes");
4}
5function voteNo() {
6 $.get("vote.cfc?method=savevote", {"key":"no"}, function() {});
7 console.log("No");
8}
And then the server side CFC publishes new chart data to the clients:
2
3 remote void function savevote(key) {
4 //Note, should probably lock this
5 if(key == "yes") application.votes.yes++;
6 else if(key == "no") application.votes.no++;
7 else abort;
8
9 msg = {"votes":application.votes};
10 wspublish("vote",msg);
11 }
12
13}
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:
2 var whiteboard = $("#whiteboard");
3 canvas = whiteboard[0].getContext("2d");
4 var offset = whiteboard.offset();
5
6 whiteboard.bind("mousedown", function(e) {
7 canvas.beginPath();
8 pointX = e.clientX-offset.left;
9 pointY = e.clientY-offset.top;
10 canvas.arc(pointX,pointY, 2, 0, Math.PI*2,false);
11 canvas.strokeStyle = "#000";
12 canvas.stroke();
13 if(oldX && oldY) {
14 canvas.lineTo(oldX,oldY);
15 canvas.stroke();
16 whiteboardWS.publish("whiteboard", {type:"draw",origin:userid, from:{x:pointX,y:pointY},to:{x:oldX,y:oldY}});
17 }
18 oldX=pointX, oldY=pointY;
19 });
20
21})
And here's my listener to draw lines from other clients:
2 //notice welcome
3 if (message.type == "response" && !userid) {
4 userid = message.utid;
5 }
6 if (message.type == "data") {
7 var data = JSON.parse(message.data);
8 //console.dir(m);
9 if(data.origin == userid) return;
10 console.dir(data);
11 canvas.beginPath();
12 canvas.moveTo(data.from.x, data.from.y);
13 canvas.lineTo(data.to.x,data.to.y);
14 canvas.stroke();
15 canvas.closePath();
16 }
17}
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.


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
@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 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
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 :)
@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.
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.
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.
[Add Comment] [Subscribe to Comments]