Jorge del Casar (a.k.a. @JorgeCasar)
HTML5 evangelist
Javascript writer
CSS3 styler
Tecnology advisor
Siesta-time speaker
Reliable "real-time" comunications with minimal latency
Make a ajax request continuously
(function poll() {
setInterval(function () {
$.ajax({
dataType: 'json',
url: 'http://somewhere.com/rest/123',
success: function (data) {
// Do something with the data
}
});
}, 5000);
})();
Make a ajax request continuously (stoppable)
(function poll() {
setTimeout(function () {
$.ajax({
dataType: 'json',
url: 'http://somewhere.com/rest/123',
success: function (data) {
// Do something with the data
if( continuePulling(data) ) {
poll();
}
}
});
}, 5000);
})();
Keep the connection open
(function longPoll() {
setTimeout(function () {
$.ajax({
dataType: 'json',
url: 'http://somewhere.com/rest/123',
success: function (data) {
// Do something with the data
longPoll();
},
timeout: 30000
});
}, 5000);
})();
WebSocket is a protocol providing full-duplex communications channels over a single TCP connection
Reducing kilobytes of data to 2 bytes…and reducing latency from 150ms to 50ms is far more than marginal. In fact, these two factors alone are enough to make WebSocket seriously interesting to Google.
Ian Hickson
Google, HTML5 spec lead
[Constructor(DOMString url, optional (DOMString or DOMString[]) protocols)]
interface WebSocket : EventTarget {
readonly attribute DOMString url;
// ready state
const unsigned short CONNECTING = 0;
const unsigned short OPEN = 1;
const unsigned short CLOSING = 2;
const unsigned short CLOSED = 3;
readonly attribute unsigned short readyState;
readonly attribute unsigned long bufferedAmount;
// networking
attribute EventHandler onopen;
attribute EventHandler onerror;
attribute EventHandler onclose;
readonly attribute DOMString extensions;
readonly attribute DOMString protocol;
void close([Clamp] optional unsigned short code, optional DOMString reason);
// messaging
attribute EventHandler onmessage;
attribute BinaryType binaryType;
void send(DOMString data);
void send(Blob data);
void send(ArrayBuffer data);
void send(ArrayBufferView data);
};
//Create new WebSocket
var mySocket = new WebSocket("ws://www.websockets.org");
// Associate listeners
mySocket.onopen = function(evt) {
alert("Connection open…");
};
mySocket.onmessage = function(evt) {
alert("Received message: " + evt.data);
};
mySocket.onclose = function(evt) {
alert("Connection closed…");
};
mySocket.onerror = function(evt) {
alert("Error");
};
// Sending data
mySocket.send("WebSocket Rocks!");
// Close WebSocket
mySocket.close();
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});