I figured out two interesting things last night:
- Using Netscape’s old buzzword, push technology, you can maintain an XHR connection to a web server and feed it new data as it comes available. Thus, no polling and no hammering your web server.
- You can get ColdFusion to tell you when a browser has disconnected from a long-running page.
What do you get when you mash the two together? Real-time browser-based chat without polling. It’s only a proof of concept and doesn’t work in anything but Firefox for now … but think of the possibilities.
Here’s basically how it works:
- The browser hits the page and loads the UI HTML.
- Two XHR/AJAX requests are made: one to announce your login and fetch a user list. The other …
- The other does all of the heavy lifting. It’s one request that just keeps pulling data as it comes in off the wire.
- When you type in a line and submit it, via another XHR, the server adds it to the chat log.
- A few times per second, the CF page that is handling the open requests wakes up and checks to make sure the outgoing queue is still empty and that the browser is still connected.
- When the outgoing queue has something in it, the page sends it and goes back to sleep.
- When the browser disconnects, the page senses it the next time it wakes up, and aborts itself. No wasted resources.
Basically, it’s a very scaled-down version of the magic that Flex/LiveCycle Data Services performs. The key is that second part — knowing when to tell CF to give up.
You can take a look at the source at Google Code: chat.cfm.
I’ve seen hacks that use IFrames to get a similar effect in Internet Explorer — flush out a page and keep checking the DOM for new nodes. That could probably be applied here. And supposedly Opera can also do the multipart magic that Firefox can do, but there’s probably something that I’m missing.