Implement Websockets
in Videogames, why for?

Jorge del Casar (a.k.a. @JorgeCasar)

Who am I?

HTML5 evangelist

Javascript writer

CSS3 styler

Tecnology advisor

Siesta-time speaker

Why?

Reliable "real-time" comunications with minimal latency

Why not HTTP?

  • HTTP is half-duplex
  • HTTP adds latency (75-140ms range)
  • HTTP overcharge headers (700-800 bytes)

Short Polling (setInterval)

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);
})();

Short Polling (setTimeOut)

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);
})();

Example polling

Long Polling (Comet)

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);
})();

Forever iframe (Streaming)

  • Loading a page in an IFRAME
  • Receives commands wrapped in <script> tags
  • Evaluate the script

Example forever iframe

Header traffic analysis

  • Case A: 10.000 clients polling every 60 seconds
    Trafic: 0,9 Mbps
  • Case B: 10.000 clients polling every second
    Trafic: 58,6 Mbps
  • Case C: 100.000 clients polling every 10 seconds
    Trafic: 58,6 Mbps

Header size calculator

Where?

  • Messaging
  • Financial
  • Monitoring and management
  • Social networking
  • Shared working
  • Gaming
  • And much more...

What?

WebSocket is a protocol providing full-duplex communications channels over a single TCP connection

http://dev.w3.org/html5/websockets/

What way?

  • Runs via port 80/443 - Proxy/Firewall friendly
    • HTTP-compatible handshake
    • Integrates with Cookie based authentication
  • WebSockets and Secure WebSockets
    • ws://
    • wss://

What traffic reduction?

  • Each message has 2 bytes of overhead
  • No latency for establishing new TCP connection
  • Only send messages when there is something to send

Header traffic analysis

  • Case A: 10.000 messages every 60 seconds
    Trafic: 2 Kbps
  • Case B: 10.000 messages every second
    Trafic: 156 Kbps
  • Case C: 100.000 messages every 10 seconds
    Trafic: 156 Kbps

Header size calculator

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

How?

WebSocket API

[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);
};

API specification

In the client

//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();

In the server (NodeJS)

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);
  });
});

When?

Now!
Let's demo!

Header size calculator

Bytes

thousand

seconds

Result:

  • 0 Bytes per second
  • 0 Kbps
Back