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://my-chat-server.com:8080/”),
me = getUsername();
socket.onmessage = function(event) {
var data = JSON.parse(event.data);
if (data.action == 'joined') {
initiliseChat();
} else {
showNewMessage(data.who, data.text);
}
};
socket.onclose = function () {
socket.send(JSON.stringify({
action: 'logoff',
username: me
}));
showDisconnectMsg();
};
socket.onopen = function() {
socket.send(JSON.stringify({
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