HTML and CSS Reference
In-Depth Information
socket.onmessage = function(event) {
var tweetNode = renderTweet(JSON.parse(event.data));
document.getElementById('tweets').appendChild(tweetNode);
};
Now in as many as four lines of JavaScript (excluding the
renderTweet function, which just massages the incoming parsed
JSON data into a workable HTML fragment to append to the
page), I've got streaming real-time tweets on my page.
TIp The URL that you
use for the WebSocket
doesn't have to be the same ori-
gin as your document. This
means you can connect to serv-
ers from third-party services,
which expands the possibilities
of what can be done.
Doing more than listening with a socket
As I said before, there are more methods available on a socket
than just listening. Since a chat application is the hello world of
Comet, I felt it only fair to show you a simple example of what
chat would look like using WebSockets:
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
}));
};
 
Search WWH ::




Custom Search