HTML5 Communications

Cross Document Messaging

XMLHttpRequest Level 2

ServerSent Event

WEBSOCKET

Cross Document Messaging

postMessage API

sender

// this is on http://sender.site              
otherWindow.postMessage("hi there", "http://receiver.site");
              
receiver

// this is on http://receiver.site
window.onmessage = function (event) {
  if (event.origin !== "http://sender.site") {
    return;
  }
  console.log('received message: ' + event.data);
};
              

whether it supports ?


if (window.postMessage) {
  console.log("postMessage not supported in this browser")
}
            

XMLHttpRequest Level 2

  • Cross-origin XMLHttpRequests
  • Progress events
  • Binary Data

ServerSent Event

Receiving data from server
              
var evtSource = new EventSource("/event-source"); 
evtSource.onmessage = function(e) {
     console.log(e.data);
}
              
Sending data from server

get "/event-source" do
     response.headers['Content-Type'] = 'text/event-stream'
     while (1) {
           return "data: message from server \n\n"
           wait_random_time
     }
end                
              

WebSocket

“Reducing kilobytes of data to 2 bytes…and reducing latency from 150 ms to 50 ms is far more than marginal. In fact, these two factors alone are enough to make WebSocket seriously interesting to Google.”

For RealTime

Protocol
allows for a persistent, full-duplex communication between a client and remote host.
HTML5
defines a JavaScript API for the WebSocket protocol within the browser, allowing bi-directional communication between the browser and server.

Why ?

Web apps need to communicate with server in real-time

Can't we already do that ?

Ajax Polling

Client sends AJAX request to server, server responds

Works When:

  • client needs to request data occasionally
  • client needs to send data occasionally

Falls short When:

  • client needs to send data often
  • server needs to iniate and send data without client request

AJAX Long-polling

Client sends AJAX request to server, server keeps request open until response available.
Client immediately sends another long-poll request after receiving response

Works When:

  • client needs to request one or a few pieces of data at a time
  • server needs to send one or a few pieces of data occastionally

Falls short When:

  • client needs to send data often
  • client needs initiate and send data when available
  • server needs to send data often

Server-Sent Events(SSE)

Client opens connection with server
Server sends data to client as it becomes available

Works When:

  • server needs to send data often
  • browser support for WebSockets can't be relied upon

Falls short When:

  • client needs to send any data

WEBSOCKETS

Client opens connection with server
Client and server send data to each other as data becomes available on either side

Works When:

  • server and/or client need to send data often
  • browser support for WebSockets can be relied upon or fallbacks can be used

Falls short When:

  • fallbacks can't be relied upon

how it works ?

HTTP Handshake

Request


GET ws://echo.websocket.org/?encoding=text HTTP/1.1
Origin: http://websocket.org
Cookie: __utma=99as
Connection: Upgrade
Host: echo.websocket.org
Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw==
Upgrade: websocket
Sec-WebSocket-Version: 13
            

Response


HTTP/1.1 101 WebSocket Protocol Handshake
Date: Fri, 10 Feb 2012 17:38:18 GMT
Connection: Upgrade
Server: Kaazing Gateway
Upgrade: WebSocket
Access-Control-Allow-Origin: http://websocket.org
Access-Control-Allow-Credentials: true
Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU=
Access-Control-Allow-Headers: content-type             
            

Full-duplex Connections

WebSocket API

URI Structure

Define new protocols, ws:// and wss://

Setup Connection


var connection = new WebSocket('ws://subdomain.examnple.com/some-endpoint')
            

Listen Event


connection.onopen = function(e) {
  console.log("Connected");
};

connection.onmessage = function(e) {
  console.log( "Received: " + e.data);
};

connection.onclose = function(e) {
  console.log("Connection closed");
};              

connection.onerror = function(e) {
  console.log("There are some errors: e.data");
};              

            

Message Date Formate

  • String
  • ArrayBuffer
  • Blob

not support JSON ?

using JSON.stringify and JSON.parse to handle it

WEBSOCKET SERVER

Many Choices

Server can be built in any language

Existed libraries for nodejs, ruby, python, php

Socket.io is awesome

Easy to use


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

Use Cases

  • Games
  • Notifications
  • Collaboration
  • Statistics
  • Chat

Demo

last mile