HTML5 WebSockets

HTML5 Powered with Connectivity / Realtime, CSS3 / Styling, and Semantics

ZendCon - Santa Clara, CA

http://spoutserver.com/talks/websockets.html

Scott Mattocks | @scottmattocks | scott@crisscott.com

Thanks http://html5rocks.com

Scott Mattocks...

  • Works for the Game Show Network
  • Cannot get you on The Price Is Right
  • Likes beer
  • Does not mind being interupted

WebSockets

The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (e.g. using XMLHttpRequest or <iframe>s and long polling). - WebSocket Protocol Draft 07

WebSockets are good for games…

…and chat…

…and monitoring…

I don't have a real time example for this one.

People don't really want to expose that information.

…and stock tickers…

When money is on the line, a 30 second delay could be very expensive.

…and sports…

It's a bit early for a live demo

…and collaboration…

Bi-directional communication is
helpful when sharing ideas.

…and real-time messaging…

Without a constant connection,
you can't call it real-time

…and interactive interfaces…

But I can do it all with AJAX!

  • You can't do it efficiently enough
  • You can't do it fast enough
A 2011 Ford AJAX 150

Should I use WebSockets?

Yes if…
  • You need the client to send messages to the server
  • You need the server to send messages to the client
  • Your sysadmin gets angry/angrier when the servers are over worked

So far

  • WebSockets are efficient
  • WebSockets allow bi-directional communication on the same connection
  • AJAX is a misuse of existing technology
WebSockets =
Client side API [CS]
(The browser)
+
WebSocket Protocol [WSP];
(The browser and the server)

The Browser...

CS
  • initiates contact
  • turns the messages from the server into something consumable by the user
  • uses the JavaScript API

The Server...

WSP
  • confirms the request validity
  • parses requests
  • sends data
  • What it does with the request and data is up to you

It's easy to get started

CS
var url    = 'ws://ws.example.com/updates';
var socket = new WebSocket(url);

What does that get us?

CS

An object with these properties

  • url
  • readyState
  • bufferedAmount
  • protocol

(sort of) readyState

CS
  • CONNECTING
  • OPEN
  • CLOSING
  • CLOSED
Image Credit: tantek

Listening to the server

CS
Image Credit: Dustin and Jenae
CS
socket.onopen = function () {
    // Process any commands that queued up
    // while we were connecting.
    var i = 0, size = this.queue.length;
    for (i; i < size; i++) {
        this.send(this.queue[i]);
    }

    // Clear the command queue.
    this.queue = [];
};
CS
socket.onmessage = function (evt) {
    // Process the message from the server
    $('#datalist').appendChild(evt.data);
};
CS
socket.onerror = function () {
    // Something bad happened. Log a message.
    console.log('WebSocket error');
};
CS
socket.onclose = function (evt) {
    // Check to see if the close was clean.
    if (!evt.wasClean) {
        console.log('WebSocket error');
    }
};

Talking to the server

Image Credit: kitcowan

Remember this?

The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (e.g. using XMLHttpRequest or <iframe>s and long polling). - WebSocket Protocol Draft 06
CS
socket.send('This message is awesome!');
CS
socket.close();

So far

  • Support is evolving
  • Event driven model for listening to the server
  • Sending data is a simple method call
It all starts with a (secret) handshake

WebSocket Handshake

WSPCS
GET /demo HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: AQIDBAUGBwgJCgsMDQ4PEC==
Sec-WebSocket-Origin: http://example.com
Sec-WebSocket-Version: 8

WebSocket Handshake Response

WSP
HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: OfS0wDaT5NoxF2gqm7Zj2YtetzM=

Creating Sec-WebSocket-Accept

$key   = 'AQIDBAUGBwgJCgsMDQ4PEC==';
$magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';

$sha1   = sha1($key . $magic, true);
$accept = base64_encode($sha1);

Frames

WSP
  • Provide a layer of security for the message
  • Identify the content types of the message
  • Indicate the size of the message
  • Allows for large messages to be sent without buffering

Frames

WSP
0223
01234567890123456789012345678901
F
I
N
R
S
V
1
R
S
V
2
R
S
V
3
opcode
(4)
M
A
S
K
Payload len
(7)
Extended payload length
(16/63)
(if payload len==126/127)
Extended payload length continued, if payload len == 127
Masking-key, if MASK set to 1
Masking-key (continued)
Payload Data
 

The End (of the connection)

WSP
  • Either end can initiate the close
  • Both ends must acknowledge the closing
Image Credit: mjb

So far

  • Handshake establishes a reliable connection
  • Message framing allows long messages to be broken into smaller chunks
  • Clean close requires help from both ends

Summary

  • Bi-directional communication
  • Lower overhead than HTTP
  • Client side is JavaScript
  • Protocol defines how the connection is opened and messages are sent
Questions?
Thanks for listening
http://joind.in/talk/view/3757