Introduction

Evolution Not Revolution.

HTML5 design principle, (W3C)

Agenda

  • Introduction
  • Connectivity and Real Time Communication
    • Who is communicating?
    • How is communication established?
    • What is communicated?
  • Questions and Answers

HTML5 Feature Areas

HTML5 Feature Areas
HTML5 badges by W3C

Who is communicating?

Web Origins

An origin consists of three parts:
Scheme, Host, and Port

Example Origins

# The following origins are all different
# (default HTTP ports 80 and 443 are used if nothing is specified):
http://www.example.com 
http://img.example.com
https://www.example.com
http://www.example.com:9999
# The origin is taken literally by browsers. For example:
http://localhost:9999
#is not the same as:
htpp://127.0.0.1:9999
# Note the new WebSocket schemes (80 and 443 are the default ports):
ws://websockets.org
wss://websockets.org
Without any security model, user agents might undertake actions detrimental to the user or to other parties. Over time, many web-related technologies have converged towards a common security model known colloquially as the same-origin policy.

The Web Origin Concept (RFC 6454)

Same Origin Policy and CORS

  • Same-origin policy can be too restrictive for modern web appps
  • Led to (vulnerable) hacks like JSONP
  • Cross Origin Resource Sharing (CORS)
    • Allows opt-in exemptions from the Same-Origin Policy
    • Allows for loosely-coupled architetures
    • Server participation required
    • Used in XHR, WebSocket, etc.
With XHR and CORS, you receive data instead of [JSONP] code, which you can parse safely
Frank Salim, Google

CORS Headers

Browser to Server:

HTTP POST /main HTTP/1.1
...
Referer: http://www.example.com/slides
Origin: http://www.example.com

Server to Browser:

# Space separated origin list
# Important: Think twice before adding *
Access-Control-Allow-Origin: http://www.example.com
Access-Control-Allow-Credentials: true

Web Intents

What is a "Web In Tent"?

Web Intents

Connectivity and Real Time Feature Area
  • A client-side framework that allows users to use their preferred applications for actions on content-types
  • Advantages:
    • No complex white-listing on both sides
    • Removes tight coupling (widgets)
    • Removes complex authorization dance (server to server)
    • Works offline
    • Simple 2-step configuration

Web Intents Example

Step 1. Show what you can do

Define the data your app can handle

{
  "name": "An app", "version": "1",
  "intents": {
    "http://webintents.org/save": [{
      "type":["image/*"],
      "href":"/save.html",
      "disposition": "inline"
    }]
  }
} 
<intent
  action="http://webintents.org/save"
  type="image/*"
  href="save.html"
  disposition="inline" />

Step 2. Prepare to receive data

if(window.webkitIntent) {
  var i = window.webkitIntent;
  if(i.action == "http://webintents.org/save") {
    if(i.type == "image/png") {
      img.src = i.data; // the data
    }
  }
} 

How is communication established?

Connectivity and Real Time Features

Connectivity and Real Time Feature Area
  • Cross Document Messaging
  • XMLHttpRequest Level 2
  • Server-Sent Events
  • WebSocket
  • WebRTC

A Note about Browser Support

Some great resources:

Cross Document Messaging

Cross Document Messaging

  • postMessage API
  • Allows you to securely send messages to another page, tab, or iFrame
  • Also used in Web Workers
  • Cross-Origin Support
  • Use caution when adding message event listeners (use an origin white list)

Cross Document Messaging Example

Example: postMessage()

Sending messages:

worker.postMessage('Hello World');
window.postMessage(JSON.stringify({msg: 'Hello World'}), 'http://www.example.com');

Receiving messages:

window.addEventListener("message", processMessage,true); 

function processMessage(e) { 
  if (e.origin == "http://www.example.com") {
    // Only process from trusted source! 
    processMessage(e.data); 
  } 
}
// Some more exciting options later...

XMLHttpRequest Level 2

XMLHttpRequest Level 2

  • New features in Level 2:
    • Cross-domain support (using CORS)
    • Named progress events (instead of numeric codes):
      • loadstart, progress, error, abort, load, loadend
    • Proper binary support XHR responseType
      (forget overriding the mime type with a user-defined charset)
      • text, blob, document, arraybuffer*
        * just deprecated in favor of typed array

XMLHttpRequest Level 2 Example

Example: XMLHttpRequest Level 2

function upload(blobOrFile) {
  var xhr = new XMLHttpRequest();
  //Can send cross domain now
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };
  xhr.send(blobOrFile);
}

Server-Sent Events

Server-Sent Events

Server-Sent Events

  • eventSource API
  • Use only when data doesn't need to be sent from the client to the server
  • Standardization of server-side push
  • Minimal overhead (tens of bytes, not hundreds)
  • HTTP based (but requires server support)

Server-Sent Events Example

Example: Server-Sent Events

//Create new EventSource
var dataStream = new EventSource("http://www.example.com");

// Add handlers for open and error:
dataStream.onopen = function(evt) { console.log("open"); } 
dataStream.onerror = function(evt) { console.log("error"); };

// Handle messages
dataStream.onmessage = function(evt) { 
  // Process message
  console.log("message: " + evt.data);
} 

WebSocket

Real Socket Power...
For the Web!

WebSocket

  • Clean standardization for complex hacks used to simulate real time, bidirectional communication
  • W3C API and IETF Protocol
  • Browser can communicate with a remote host (CORS)
  • Allows for higher-level protocol communication (for example, chat, messaging)
  • Need server support
    See my DZone WebSocket Refcard for complete list of servers

Bidirectional Browser Communication At Last!

So, what about SPDY?

The right tool for the job

"I use the metaphor of hammers and screwdrivers. Both tools are indispensible in my workshop...

Use the right tool for the job.
In the case of page and object delivery use SPDY.
In the case of lightweight or streaming data delivery look to WebSocket."

Stephen Ludin, Chief Product Architect
Akamai (Blog post)

WebSocket, WebGL, and Device Orientation Example

Example: WebSocket

// Create new WebSocket, connect to ws://echo.websocket.org
var exampleSocket = new WebSocket("ws://echo.websocket.org");

// Send messages:
exampleSocket.send("Hello world"); 

// Listen for messages
exampleSocket.onmessage = function (event) {  
  console.log(event.data);  
}

// Add listeners for the other events:
exampleSocket.onopen = function(evt) { onOpen(evt) }; 
exampleSocket.onclose = function(evt) { onClose(evt) }; 
exampleSocket.onerror = function(evt) { onError(evt) };

WebSocket Debugging in Chrome Dev. Tools

Example
Use Chrome Developer Tools (Command + Option + I)

WebRTC

WebRTC

WebRTC Example

What is communicated?

Strings, JSON, Typed Arrays,
Media Streams, oh My!

What's Going over the Wire?

  • Strings
  • JSON
  • Complex, binary data:
    • Typed Arrays (Array Buffers)*
    • Media Streams

Example: postMessage()

1. Basic strings

worker.postMessage('Hello World');
window.postMessage(JSON.stringify({msg: 'Hello World'}), 'http://www.example.com');

2. JSON

worker.postMessage({msg: 'Look! no strings attached.'}, 'http://www.example.com');

Example: postMessage()

3. Complex types (File, Blob, ArrayBuffer) via structured cloning

var data = [1, 2, 3, 4];

// Blob() in Chrome 20, FF 13
worker.postMessage(new Blob(data.toString(), {type: 'text/plain'}));

var uint8Array = new Uint8Array(data);
worker.postMessage(uint8Array);
worker.postMessage(uint8Array.buffer);
  • Problem: all of these methods are copies, so not too efficient...

Transferable Objects

Transferable Objects

Same old friend, different semantics:

// Note: Prefixed for the moment
worker.webkitPostMessage(arrayBuffer, [arrayBuffer]);
window.webkitPostMessage(arrayBuffer, targetOrigin, [arrayBuffer]);
  • Zero-copy
    • Ownership of data (ArrayBuffer) is transfered to new context (e.g. worker/window). Source buffer becomes unavailable.
    • ~50x faster than structured cloning (Chrome 13/FF).
  • 2nd argument is list of what to transfer.

Demo: Transferable Objects

Questions?

San Francisco HTML5 User Group

Free monthly events, livestreamed and video taped

Google Developers Live

Follow the Chrome Developers Channel Live!

Get the Book!

Pro HTML5 Programming (Apress, 2011)

Thank You!