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

ConFoo

Scott Mattocks - February 27, 2013

@scottmattocks - scott@crisscott.com https://joind.in/8129

What are 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). - RFC 6455 (WebSocket Protocol)

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…

 

…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
  • You or your sysadmin gets angry/angrier when the systems and networks are over worked

So far

 

  • WebSockets are efficient
  • WebSockets allow bi-directional communication on the same connection
  • AJAX is a misuse of existing technology

 

 

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 (maybe)
  • sends data (maybe)
  • 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
  • extensions
  • binaryType

(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). - RFC 6455 (WebSocket Protocol)

 

 

socket.send('This message is awesome!');

 

 

socket.close();

So far

 

 

  • Support is evolving (mostly there)
  • 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 /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13

WebSocket Handshake Response

WSP
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

 

Creating Sec-WebSocket-Accept

$key   = 'dGhlIHNhbXBsZSBub25jZQ==';
$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

We're Hiring!

Great Benefits

  • Unlimited vacation and sick time
  • 401K matching
  • Hack day every 5 weeks

No Such Thing as Routine

  • DAUs measures in millions
  • Web, Mobile, and Social
  • PHP, Perl, Unity, Objective-C, Java, MongoDB…

Locations

  • Waltham, MA — Washington, D.C. — San Francisco, CA — Your house
  • We sponsor visas