HTML and CSS Reference
In-Depth Information
Doing more than listening with a socket
As I said before, there are more methods available on a socket
over just listening. Since chat is the hello world of Comet, I felt it
only fair to show you a simple example of what chat would look
like using Web Sockets:
var socket = new WebSocket(“ws://”),
me = getUsername();
socket.onmessage = function(event) {
var data = JSON.parse(;
if (data.action == 'joined') {
} else {
showNewMessage(data.who, data.text);
socket.onclose = function () {
action: 'logoff',
username: me
socket.onopen = function() {
action: 'join',
username: me
This simple pseudo code shows you how the same techniques
we used in the Message API can help to get around the limita-
tions of plain text. The Web Sockets API really is as simple as
that. All the negotiation is done out of sight by the browser for
you; all the buffering is done for you (though you can check the
current bufferedAmount on the socket). In fact, the communica-
tion process is even easier than setting up an XHR object!
Search WWH ::

Custom Search