SlideShare a Scribd company logo
1 of 82
HTML5 Real-Time and
                                                            Connectivity

                                                                                       @peterlubbers
                                                                                             Kaazing
                       Creators of WebSocket                                               WebSocket Gateway

    High Performance                                                  HTML5 Training




1                       Copyright © 2012 Kaazing Corporation. All Rights Reserved.     Illustration by Will Phillips Jr.
About @peterlubbers


       Sr. Director Technical Communication
        Kaazing (we’re hiring)
       Author, Pro HTML5 Programming
       HTML5… it’s how I roll




2                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Agenda


     Web Origin Concept
     Cross Document Messaging                                                  #sfhtml5
                                                                              @peterlubbers
     CORS
    XMLHttpRequest Level 2
    WebSocket
     Server-Sent Events
     SPDY



3                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
HTML5 Feature Areas




           "HTML5 should not be considered as a whole.
         You should cherry-pick the technology that suits the
                     solution to your problem.”
           —Remy Sharp (Co-Author Introducing HTML5)
4                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
HTML5 Feature Areas




5               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Tonight’s Focus




6                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
HTML5 Paves the Cow Paths

        HTML5 takes a pragmatic approach, fixing
         real-world problems
        Especially true for connectivity features




7                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Web Origins




8                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.   Credit: http://singleorigin.com.au/
Web Origin Concept


       Web Origin Concept RFC 6454:
        http://www.ietf.org/rfc/rfc6454.txt
       An Origin is a subset of an address used for
        modeling trust relationships on the web
       Origins consist of a scheme, a host, and a port:
         • Scheme: http:, https:, ws:, wss:
         • Host: www.example.com,
           img.example.com, 192.0.2.10
         • Port: 80, 443


9                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Same-Origin Policy

     “Generally speaking, documents retrieved from distinct
      origins are isolated from each other” –W3C
     http://www.w3.org/Security/wiki/Same_Origin_Policy

      Browsers prevent a script or document loaded
       from one origin from communicating with a
       document loaded from another origin
      Original security model for HTML
         • Introduced in Netscape Navigator 2.0
         • Too limiting in this age of client-side web apps




10                       Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Origin Quiz (Win a Book)


     Which URLs have the same Origin?
       1.   http://www.example.com/index.html
       2.   https://www.example.com/index.html
       3.   http://img.example.com/html5.png
       4.   http://www.example.com:8080/page2.html
       5.   http://192.0.2.10:80/index.html*
       6.   http://www.example.com/about.html


        *   Where 192.0.2.10 resolves to www.example.com



11                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Cross Document Messaging




12               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Cross Document Messaging


        Enables secure cross-origin communication
         across iframes, tabs, and windows
        Uses Origin security
        Defines PostMessageAPI to send messages
         (also used in Web Workers)
        Pass messages asynchronously between
         JavaScript contexts
        Demo: DZSLides (Paul Rouget, Mozilla):
         http://paulrouget.com/dzslides/

13                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
PostMessage Architecture




14               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Using PostMessage


     Sending a message
     JavaScript

           myFrame.contentWindow.postMessage
           ('Hello, world', 'http://www.example.com/');




          myFrame.contentWindowdestination
          http://www.example.comtarget origin




15                     Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Using PostMessage


      Processing a message
     JavaScript

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

        function messageHandler(e) {
            if (e.origin == "http://portal.example.com") {
        processMessage(e.data);
            }
            // ignore message if origin not recognized
        }




16                   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Handlewith Care


      Warning: “Use of this API requires extra care to
       protect users from hostile entities abusing
       a site for their own purposes” —WHATWG Spec
       http://goo.gl/en4l0
      Receiver should decide to process messages
       based on a whitelist
       of trusted origins
      Also treat message data
       with caution
       (even from trusted
       sources)

17                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Using a Whitelist


     JavaScript

        varallowedOrigins = ["http://portal.example.com/",
        "http://games.example.com:8000/"];


        function messageHandler(e) {
        if(allowedOrigins.indexOf(e.origin) >= 0) {
        processMessage(e.data);
         }
         // index will be -1 for unrecognized origins
        }

        Window.addEventListener("message", messageHandler,
        true);



18                   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Browser Support

     Native                                        Emulation
      Chrome 2.0+                                  EasyXDM
      Firefox 3.5+                                  http://easyxdm.net/
      IE 8.0+                                      KaazingWebSocket

      Opera 9.6+
                                                     Gateway
      Safari 4.0+                              http://caniuse.com/#search=postmessage




19               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
CORS




                                                         enable-cors.org



20          Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Working with Multiple Origins

        JSON with Padding (JSONP)
         • JSON data in executable Javascript wrapper
         • <script> is exempt from single-origin policy
         • Avoid if possible (vulnerable)
         HTML5 introduces Cross-Origin Resource Sharing
          (CORS)
         CORS allows exemptions from the Same-Origin
          Policy
         “With XHR and CORS, you receive data instead of
          code, which you can parse safely”
          —Frank Salim
21                   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Cross-Origin Requests


        Have an Originheader
         •   Contains the request’s origin
         •   Produced by the browser
         •   Cannot be changed by application code
         •   Differs from referer[sic]: refereris a complete
             URL (can include full path)
        Originating page’s server must approve
         (Access-Control-Allow-* headers)


22                     Copyright © 2012 Kaazing Corporation. All Rights Reserved.
CORS vs. Same Origin




23                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Origin Header (Client Request)

     HTTP

      POST /main HTTP/1.1
      Host: www.example.net
      User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US;
      rv:1.9.1.3) Gecko/20090910 Ubuntu/9.04 (jaunty)
      Shiretoko/3.5.3
      Accept:
      text/html,application/xhtml+xml,application/xml;q=0.9,*
      /*;q=0.8
      Accept-Language: en-us,en;q=0.5
      Accept-Encoding: gzip,deflate
      Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
      Keep-Alive: 300
      Connection: keep-alive
      Referer: http://www.example.com/path
      Origin: http://www.example.com
      Pragma: no-cache
24                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Access Control Headers (Server Response)


     HTTP

      HTTP/1.1 201 Created
      Transfer-Encoding: chunked
      Server: Kaazing Gateway
      Date: Mon, 02 Nov 2009 06:55:08 GMT
      Content-Type: text/plain
      Access-Control-Allow-Origin: http://www.example.com
      Access-Control-Allow-Credentials: true




25                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Browser Support

      Native                                       Server Support:
       Chrome 4.0+                                 Use a CORS-aware
       Firefox 3.5+
                                                      server
                                                    Add Access-Control-
       Safari 4.0+
                                                      Allow-Origin header
       IE 8+* 10+                                    to server config.
       Opera 12+                                                     http://caniuse.com/#search=CORS




     *partial via XDomainRequest
26                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
XMLHttpRequest Level 2




27               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
XMLHttpRequest Level 2 Improvements


        XMLHttpRequest (XHR) made Ajax possible
        Level 2 significantly enhances XMLHttpRequest
          • Progress events
          • Cross-origin XMLHttpRequest
          • Binary support
        Specification:
          • http://www.w3.org/TR/XMLHttpRequest/



28                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Progress Events


      In the past: inconsistently
                                 implemented across browsers
       e.g. readyState 3 (progress) never fires in IE
     XMLHttpRequest Level 2 adds progress events:
        •   loadstart
        •   progress
        •   abort
        •   error
        •   load
        •   loadend
     readyState   property and
     readystatechange events retained for
       backward compatibility
29                      Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Progress Events

       Fields for:
            • The total amount of data to transfer
            • The amount that has already transferred (use new
              HTML5 progress element)
            • Whether the total is known
     JavaScript
        crossOriginRequest.upload.onprogress = function(e) {
            var total = e.total;
            var loaded = e.loaded;

             if (e.lengthComputable) {
                 // do something with the progress information
             }
        }

30                      Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Cross-Origin XMLHttpRequest


     JavaScript

        //from http://www.example.com
        var crossOriginRequest = new XMLHttpRequest();
        crossOriginRequest.open("GET",
        "http://www.example.net/stockfeed", true);




       * Requires CORS-enabled server (to handle origin and
         Access Control headers)




31                     Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Binary Data

          Supports Blob and ArrayBuffer (aka Typed Array) objects
          Good for for WebGL, programmable audio, etc.
          Demo:
           http://www.html5rocks.com/en/tutorials/file/xhr2/

     JavaScript


           //Sending a Typed Array of bytes
           var a = new Uint8Array([8,6,7,5,3,0,9]);
           varxhr = new XMLHttpRequest();
           xhr.open("POST", "/data/", true)
           xhr.send(a.buffer);




32                        Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Browser Support: XHR Level 2

       Native                                                IE 8+ supports XDR
        Chrome 2.0+                                         Server side
        Firefox 3.5+                                         participation may be
        Safari 4.0+
                                                              required (CORS)
        Opera 12+
                                                    http://caniuse.com/#search=XMLHTTPRequest
        IE 8+* 10+




     *partial via XDomainRequest
33                        Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket




34               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
If You Want to Build Web Apps for…


        Financial trading
        Social networking
        Gaming
        Gambling
        System monitoring
        RFID tracking
        …WebSocket will be useful


35                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Previous Approaches


        Comet and Reverse Ajax
        Based on HTTP
        HTTP is stateless
         and half-duplex




36                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Overhead


        HTTP is stateless, results in HTTP header overhead
        Example:




          • Type one character: ~1500 characters exchanged
        Example:
         http://syntensity.com/static/espeak.html

37                   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
HTTP Request Headers

     Client


        GET /PollingStock//PollingStock HTTP/1.1
        Host: localhost:8080
        User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
        rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5
        Accept:
        text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
        Accept-Language: en-us
        Accept-Encoding: gzip,deflate
        Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
        Keep-Alive: 300
        Connection: keep-alive
        Referer: http://localhost:8080/PollingStock/
        Cookie: showInheritedConstant=false;
        showInheritedProtectedConstant=false; showInheritedProperty=false;
        showInheritedProtectedProperty=false; showInheritedMethod=false;
        showInheritedProtectedMethod=false; showInheritedEvent=false;
        showInheritedStyle=false; showInheritedEffect=false;




38                      Copyright © 2012 Kaazing Corporation. All Rights Reserved.
HTTP Response Headers

     Server

        HTTP/1.x 200 OK
        X-Powered-By: Servlet/2.5
        Server: Sun Java System Application Server 9.1_02
        Content-Type: text/html;charset=UTF-8
        Content-Length: 321
        Date: Sat, 07 Nov 2009 00:32:46 GMT




       • Total overhead: 871 bytes (example)
       • Often 1.5K+ bytes (for example,
         cookie data)
       • Overhead is expensive!

39                       Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Upload/Download Ratios


      Most users have Internet connections where
      upload to download ratios are between 1:4
      and 1:20
       •Result: 500 byte
        HTTP request header
        request could
        take as long
        to upload as
        10 kB of HTTP
        response data
        takes to download


40                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Enter WebSocket


      W3C API (Javascript)
      IETF Protocol
      Full-duplex (bi-
       directional), single
       socket
      Shares port with
       existing HTTP content
      Schemes: ws:// and
       wss://

41                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Using the WebSocket API

     JavaScript

        //Create new WebSocket
        var mySocket = new WebSocket("ws://www.WebSocket.org");

        // Associate listeners
        mySocket.onopen = function(evt) {
        };
        mySocket.onclose= function(evt) {
          alert("closed w/ status: " + evt.code};
        };
        mySocket.onmessage = function(evt) {
         alert("Received message: " + evt.data);
        };
        mySocket.onerror = function(evt) {
          alert("Error);
        };



42                   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Using the WebSocket API

     JavaScript

        // Sending data
        mySocket.send("WebSocket Rocks!");

        // Close WebSocket
        mySocket.close();




43                   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Checking for Feature Support

     JavaScript

        var status = document.getElementById("support");
        if (window.WebSocket) { // or Modernizr.websocket
        status.innerHTML = "HTML5 WebSocket is supported";
        } else {
        status.innerHTML = "HTML5 WebSocket is not supported";
        }




44                   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket History


        Originally added to HTML5 Spec as
         TCPConnection
        Moved to its
         own specification




45                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Protocol History

     “draft-hixie-thewebsocketprotocol-xx” IETF Network Working Group
     Version        Date                          Details
     -00            Jan. 9 2009                   • Initial version
     -52            Oct. 23 2009                  • Subprotocol concept introduced
     -76            May 6 2010                    • Used in older browsers (FF4, etc.)

     “draft-ietf-hybi-thewebsocketprotocol-xx” (IETF HyBi Working Group)
     Version       Date                           Details
     -01           Aug. 31 2010                   • Added binary format
     -04           Jan. 11 2011                   • Introduced data masking to address proxy
                                                    server security issue
                                                  • Introduced including protocol version number
                                                    in handshake
     RFC 6455      Dec. 2011                      • Final version
                                                     http://tools.ietf.org/html/rfc6455
46                         Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Handshake




47              Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Frames

      •   Have a few header bytes
      •   Text or binary data
      •   Frames are maskedfrom client to server




48                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Frames

     Wireshark Trace of WebSocket Basics Lab Message (Client to Server)




                                        FIN bit, MASK bit,
                                      RSV bits, Op- payload           mask             payload
                                         Code        length

                                            81 85 CB 6E 9F 8E 83 0B F3 E2 A4

                                                                               83 0B F3 E2 A4
                                                                             XOR CB 6E 9F 8E CB
                                                                               -- -- -- -- --
                                                                               48 65 6C 6C 6F
                                                                                H ello

49                       Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Frames

     Wireshark Trace of WebSocket Basics Lab Message (Server to Client)




                                                               FIN bit, MASK bit,
                                                             RSV bits, Op- payload   payload
                                                                Code        length

                                                                  81 05 48 65 6C 6C 6F
                                                                      H e l l o




50                      Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Efficiency

                       HTTP                                         WebSocket
     Overhead          100s of bytes                                2-6 bytes (typical)
     Latency           New connection                               None: Use existing
                       each time                                    connection
     Latency           Wait for next                                No waiting
     (polling)         interval
     Latency           None, if request                             No waiting
     (long polling)    sent earlier
                       + time to set up
                       next request

51                    Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Polling vs. WebSocket




52                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Latency Benchmark



           Using Comet                                         Using WebSocket




               http://webtide.intalio.com/2011/09/cometd-2-4-0-websocket-benchmarks/

53                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Browser Support

     Native:                 Emulation:
     • Chrome 4+             • KaazingWebSocket
     • Safari 5+               Gateway
     • Firefox 4+            • socket.io

     • Opera 10.7+           • SockJS

     • Internet Explorer 10+ • web-socket.js (Flash)
                                                         http://caniuse.com/#search=WebSocket




54               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Servers and Client Libraries


        Kaazing                                Misultin                             Client Libraries
        Socket.io (node.js)                    Cowboy                                Web-socket-js (JavaScript)
        Apache-websocket                       YAWS                                  AS3 WebSocket (ActionScript)
        Cramp                                  Juggernaut                            .NET WebSocket client (.NET)
        Nowjs                                  PHP Websocket                         Anaida (.NET)
        SockJS                                 websockify                            WebSocket Sharp (.NET)
        SuperWebSocket                         ActiveMQ                              Silverlight WebSocket client
        Jetty                                  HornetMQ                              Java WebSocket Client
        Atmosphere                             phpwebsocket                          Arduino C++ WebSocket client
        APE Project                            Protocol::WebSocket                   Ruby-web-socket
        Xsockets                               em-websocket                          ZTWebSocket (Objective-C)
        Orbited                                Jwebsocket                            Libwebsockets (C)
        Atmosphere                             WaterSprout Server
        Autobahn                               Pywebsocket
        CouchDB                                And more…



55                             Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Extending WebSocket

        Once you have WebSocket, you can extend
         client-server protocols to the web:
             Chat: XMPP (Jabber), IRC
             Pub/Sub (Stomp/AMQP)
             VNC (RFB)
             Any TCP-based protocol
        Browser becomes a first-class network citizen
        Real-world intermediaries can mess with traffic
         (best practice is to use WebSocket Secure)

56                     Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket and (Dreaded) Proxy Servers




                                                 http://www.infoq.com/articles/Web-Sockets-Proxy-Servers




57               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
ws:// and wss:// schemes




58               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Traditional Architecture




59                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Architecture




     100% Hipster




60                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Quiz (Win a Book)


     Which has more trouble with an unencrypted
        (ws://) connection?
     1. Transparent proxies
     2. Explicit proxies
     3. Squid proxies
     4. Firewalls




61                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Server Sent Events




62                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Server-Sent Events

         Standardizes sending a continuous
          stream of data from server to browser
         Compatible with most setups using HTTP
         EventSource API
         Great for newsfeeds, one-way stream of
          data
         SSE-specific features:
          • Automatic reconnection
          • Event IDs

63                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
SSE Architecture




64                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Using the EventSource API


     JavaScript

         if (!!windows.EventSource) { // or
         Modernizr.eventsource
         var stream = new EventSource("http://example.com");

           //Events
         stream.onopen = function() { log("open"); }
         stream.onmessage = function(evt) {
         log("message: " + evt.data); }
         stream.onerror = function(evt) {
             if (evt.eventPhase != EventSource.CLOSED) {
         log("error");
         }}};


65                   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Example: News Broadcast




                            http://kaazing.me/
66               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Browser Support

     Native:                                    Emulation:
     • Chrome 6+                                • EventSource.js (Remy
     • Safari 5+                                  Sharp)
     • Firefox 6+                                 http://goo.gl/FyanG
     • Opera 10.6+                              • KaazingWebSocket
                                                  Gateway
                                                      http://caniuse.com/#search=eventsource




67               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
                                                                                 ?
SPDY


     Pronounce: ˈspēdē
                    -




68              Copyright © 2012 Kaazing Corporation. All Rights Reserved.
SPDY


        Not an acronym (name shows how
         compression can help improve speed: SPeeDY)
        New Application Layer Protocol to “make the
         web faster”
         • Reduce page load
           times by ~50%
         • Augments HTTP
           (Not a replacement)
         • Uses HTTP-like
           request-response setup

69                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
SPDY Features

        HTTP header compression (85%-88% reduction)
        Always over TLS
        Next Protocol Negotiation (NPN)
        Request
         prioritization
        Server push
        Multiplex
         logical HTTP
         (or WebSocket)
70                   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
SPDY Advantages


        Better than HTTP pipelining
          • Not on by default, difficult to deploy
          • Head of Line Blocking issues
        Single TCP connection
         (works around
         connection limits
         per origin, less need for
         subdomains, Data URIs


71                    Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Why use TLS/port 443?


      Encrypted tunnel allows traversal of
       intermediaries
      Less overhead than originally thought
      You need secure communication anyway
      Using standard, open ports has a big advantage
     "We want some chance of
       getting this protocol out
       in our live time”
       —Roberto Peon (Google)

72                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
SPDY in Chrome

        Default (95% of the time)
        WebSocket over SPDY, use command line
         switch in Google Chrome:
         --enable-websocket-over-spdy




                                            chrome://net-internals/#spdy
73                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
SPDY in Firefox


        Since version 11 preference in about:config:
         network.http.spdy.enabled
        Default in version 13




74                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
HTTP Strict Transport Security



        Forces browser to use HTTPS
         • Not simply HTTPredirectHTTPS
         • Address rewritten before request
        Enable with Strict-Transport-Security
         header
        Browser support: FF4+, Chrome
        References:
         • mikewest.org/2011/10/http-strict-transport-security-and-you
         • tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-02


75                      Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Questions?




     •   E-mail: peter.lubbers@kaazing.com
     •   Twitter: @peterlubbers
     •   LinkedIn: Peter Lubbers
76                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Announcing the HTML5 Code Labs


        Series of three Code Labs:
          • March 7
          • April 10
          • May 5 (HTML Cinco!)
        In conjunction with GTUGSF
        Sign up:
         http://GTUGsf.com/HTML5


77                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Buy the Book!


     •   Pro HTML5 Programming (Apress, 2011)
     •   50% off e-book coupon code:
         50OFFHTML5
         http://goo.gl/Dzq4A




78                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Additional Resources

        Scheme host port blog (Adam Barth):
         http://www.schemehostport.com/
        SPDY Essentials (Google Tech Talk):
         http://goo.gl/IcVdF
        Breaking the Cross Domain Barrier (Alex Slexton):
         http://goo.gl/IcVdF
        SPDY whitepaper:
         http://dev.chromium.org/spdy/spdy-whitepaper
        XHR Level 2 Article (Eric Bidelman):
         http://www.html5rocks.com/en/tutorials/file/xhr2/
        HTML5 Weekly:
         http://html5weekly.com/
        The Web Ahead Podcasts:
         http://5by5.tv/webahead/
79                      Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Get Trained!


        Proven, practical worldwide HTML5 Training
         (from experts, not just trainers):
         • E-mail us: training@kaazing.com
         • Web site: http://kaazing.com/training/




80                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
-
81   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Quiz Answers


        Origins 1 and 6 are the same
        Transparent Proxies




82                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.

More Related Content

What's hot

HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs Silverlight
Matt Casto
 
Getting started with Catalyst and extjs
Getting started with Catalyst and extjsGetting started with Catalyst and extjs
Getting started with Catalyst and extjs
Peter Edwards
 

What's hot (20)

Apache httpd v2.4
Apache httpd v2.4Apache httpd v2.4
Apache httpd v2.4
 
Best node js course
Best node js courseBest node js course
Best node js course
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Node JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web AppNode JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web App
 
HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs Silverlight
 
Scaling Django
Scaling DjangoScaling Django
Scaling Django
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
 
Aligning Ember.js with Web Standards
Aligning Ember.js with Web StandardsAligning Ember.js with Web Standards
Aligning Ember.js with Web Standards
 
Getting started with Catalyst and extjs
Getting started with Catalyst and extjsGetting started with Catalyst and extjs
Getting started with Catalyst and extjs
 
Node.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scaleNode.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scale
 
Hack & Fix, Hands on ColdFusion Security Training
Hack & Fix, Hands on ColdFusion Security TrainingHack & Fix, Hands on ColdFusion Security Training
Hack & Fix, Hands on ColdFusion Security Training
 
Plack at YAPC::NA 2010
Plack at YAPC::NA 2010Plack at YAPC::NA 2010
Plack at YAPC::NA 2010
 
Web Development with NodeJS
Web Development with NodeJSWeb Development with NodeJS
Web Development with NodeJS
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaJavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
 
Keypoints html5
Keypoints html5Keypoints html5
Keypoints html5
 
Developing web applications in 2010
Developing web applications in 2010Developing web applications in 2010
Developing web applications in 2010
 
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 

Similar to HTML5 Real-Time and Connectivity

W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
Brad Hill
 
Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5
DefconRussia
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketV2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocket
brent bucci
 
Secure web messaging in HTML5
Secure web messaging in HTML5Secure web messaging in HTML5
Secure web messaging in HTML5
Krishna T
 
How Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web DevelopmentHow Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web Development
Bruno Borges
 

Similar to HTML5 Real-Time and Connectivity (20)

HTML5 WebSocket Introduction
HTML5 WebSocket IntroductionHTML5 WebSocket Introduction
HTML5 WebSocket Introduction
 
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
 
Top 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud DevelopersTop 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud Developers
 
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
 
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/CamelCamelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the Future
 
Html5 Application Security
Html5 Application SecurityHtml5 Application Security
Html5 Application Security
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
 
It is not HTML5. but ... / HTML5ではないサイトからHTML5を考える
It is not HTML5. but ... / HTML5ではないサイトからHTML5を考えるIt is not HTML5. but ... / HTML5ではないサイトからHTML5を考える
It is not HTML5. but ... / HTML5ではないサイトからHTML5を考える
 
Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketV2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocket
 
Programming WebSockets with Glassfish and Grizzly
Programming WebSockets with Glassfish and GrizzlyProgramming WebSockets with Glassfish and Grizzly
Programming WebSockets with Glassfish and Grizzly
 
XSS Without Browser
XSS Without BrowserXSS Without Browser
XSS Without Browser
 
Secure web messaging in HTML5
Secure web messaging in HTML5Secure web messaging in HTML5
Secure web messaging in HTML5
 
Browser Security
Browser SecurityBrowser Security
Browser Security
 
How Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web DevelopmentHow Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web Development
 
Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.
 
IE 8 et les standards du Web - Chris Wilson - Paris Web 2008
IE 8 et les standards du Web - Chris Wilson - Paris Web 2008IE 8 et les standards du Web - Chris Wilson - Paris Web 2008
IE 8 et les standards du Web - Chris Wilson - Paris Web 2008
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaHTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun Gupta
 
Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
Going Beyond Cross Domain Boundaries (jQuery Bulgaria)Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
 

More from Peter Lubbers

Peter lubbers-html5-overview-sf-dev-conf-2011
Peter lubbers-html5-overview-sf-dev-conf-2011Peter lubbers-html5-overview-sf-dev-conf-2011
Peter lubbers-html5-overview-sf-dev-conf-2011
Peter Lubbers
 
HTML5 Web Workers-unleashed
HTML5 Web Workers-unleashedHTML5 Web Workers-unleashed
HTML5 Web Workers-unleashed
Peter Lubbers
 

More from Peter Lubbers (8)

Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)
 
Peter lubbers-html5-overview-sf-dev-conf-2011
Peter lubbers-html5-overview-sf-dev-conf-2011Peter lubbers-html5-overview-sf-dev-conf-2011
Peter lubbers-html5-overview-sf-dev-conf-2011
 
High-Speed HTML5
High-Speed HTML5High-Speed HTML5
High-Speed HTML5
 
HTML5: The Next Internet Goldrush
HTML5: The Next Internet GoldrushHTML5: The Next Internet Goldrush
HTML5: The Next Internet Goldrush
 
HTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the WebHTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the Web
 
Los Angeles HTML5 User Group Meeting Ask the Expert Session
Los Angeles HTML5 User Group Meeting Ask the Expert SessionLos Angeles HTML5 User Group Meeting Ask the Expert Session
Los Angeles HTML5 User Group Meeting Ask the Expert Session
 
HTML5 Web Workers-unleashed
HTML5 Web Workers-unleashedHTML5 Web Workers-unleashed
HTML5 Web Workers-unleashed
 
HTML5--The 30,000' View (A fast-paced overview of HTML5)
HTML5--The 30,000' View (A fast-paced overview of HTML5)HTML5--The 30,000' View (A fast-paced overview of HTML5)
HTML5--The 30,000' View (A fast-paced overview of HTML5)
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

HTML5 Real-Time and Connectivity

  • 1. HTML5 Real-Time and Connectivity @peterlubbers Kaazing Creators of WebSocket WebSocket Gateway High Performance HTML5 Training 1 Copyright © 2012 Kaazing Corporation. All Rights Reserved. Illustration by Will Phillips Jr.
  • 2. About @peterlubbers  Sr. Director Technical Communication Kaazing (we’re hiring)  Author, Pro HTML5 Programming  HTML5… it’s how I roll 2 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 3. Agenda  Web Origin Concept  Cross Document Messaging #sfhtml5 @peterlubbers  CORS XMLHttpRequest Level 2 WebSocket  Server-Sent Events  SPDY 3 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 4. HTML5 Feature Areas "HTML5 should not be considered as a whole. You should cherry-pick the technology that suits the solution to your problem.” —Remy Sharp (Co-Author Introducing HTML5) 4 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 5. HTML5 Feature Areas 5 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 6. Tonight’s Focus 6 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 7. HTML5 Paves the Cow Paths  HTML5 takes a pragmatic approach, fixing real-world problems  Especially true for connectivity features 7 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 8. Web Origins 8 Copyright © 2012 Kaazing Corporation. All Rights Reserved. Credit: http://singleorigin.com.au/
  • 9. Web Origin Concept  Web Origin Concept RFC 6454: http://www.ietf.org/rfc/rfc6454.txt  An Origin is a subset of an address used for modeling trust relationships on the web  Origins consist of a scheme, a host, and a port: • Scheme: http:, https:, ws:, wss: • Host: www.example.com, img.example.com, 192.0.2.10 • Port: 80, 443 9 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 10. Same-Origin Policy “Generally speaking, documents retrieved from distinct origins are isolated from each other” –W3C http://www.w3.org/Security/wiki/Same_Origin_Policy  Browsers prevent a script or document loaded from one origin from communicating with a document loaded from another origin  Original security model for HTML • Introduced in Netscape Navigator 2.0 • Too limiting in this age of client-side web apps 10 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 11. Origin Quiz (Win a Book) Which URLs have the same Origin? 1. http://www.example.com/index.html 2. https://www.example.com/index.html 3. http://img.example.com/html5.png 4. http://www.example.com:8080/page2.html 5. http://192.0.2.10:80/index.html* 6. http://www.example.com/about.html * Where 192.0.2.10 resolves to www.example.com 11 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 12. Cross Document Messaging 12 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 13. Cross Document Messaging  Enables secure cross-origin communication across iframes, tabs, and windows  Uses Origin security  Defines PostMessageAPI to send messages (also used in Web Workers)  Pass messages asynchronously between JavaScript contexts  Demo: DZSLides (Paul Rouget, Mozilla): http://paulrouget.com/dzslides/ 13 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 14. PostMessage Architecture 14 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 15. Using PostMessage Sending a message JavaScript myFrame.contentWindow.postMessage ('Hello, world', 'http://www.example.com/');  myFrame.contentWindowdestination  http://www.example.comtarget origin 15 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 16. Using PostMessage Processing a message JavaScript window.addEventListener("message", messageHandler,true); function messageHandler(e) { if (e.origin == "http://portal.example.com") { processMessage(e.data); } // ignore message if origin not recognized } 16 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 17. Handlewith Care  Warning: “Use of this API requires extra care to protect users from hostile entities abusing a site for their own purposes” —WHATWG Spec http://goo.gl/en4l0  Receiver should decide to process messages based on a whitelist of trusted origins  Also treat message data with caution (even from trusted sources) 17 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 18. Using a Whitelist JavaScript varallowedOrigins = ["http://portal.example.com/", "http://games.example.com:8000/"]; function messageHandler(e) { if(allowedOrigins.indexOf(e.origin) >= 0) { processMessage(e.data); } // index will be -1 for unrecognized origins } Window.addEventListener("message", messageHandler, true); 18 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 19. Browser Support Native Emulation  Chrome 2.0+  EasyXDM  Firefox 3.5+ http://easyxdm.net/  IE 8.0+  KaazingWebSocket  Opera 9.6+ Gateway  Safari 4.0+ http://caniuse.com/#search=postmessage 19 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 20. CORS enable-cors.org 20 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 21. Working with Multiple Origins  JSON with Padding (JSONP) • JSON data in executable Javascript wrapper • <script> is exempt from single-origin policy • Avoid if possible (vulnerable)  HTML5 introduces Cross-Origin Resource Sharing (CORS)  CORS allows exemptions from the Same-Origin Policy “With XHR and CORS, you receive data instead of code, which you can parse safely” —Frank Salim 21 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 22. Cross-Origin Requests  Have an Originheader • Contains the request’s origin • Produced by the browser • Cannot be changed by application code • Differs from referer[sic]: refereris a complete URL (can include full path)  Originating page’s server must approve (Access-Control-Allow-* headers) 22 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 23. CORS vs. Same Origin 23 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 24. Origin Header (Client Request) HTTP POST /main HTTP/1.1 Host: www.example.net User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090910 Ubuntu/9.04 (jaunty) Shiretoko/3.5.3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,* /*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://www.example.com/path Origin: http://www.example.com Pragma: no-cache 24 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 25. Access Control Headers (Server Response) HTTP HTTP/1.1 201 Created Transfer-Encoding: chunked Server: Kaazing Gateway Date: Mon, 02 Nov 2009 06:55:08 GMT Content-Type: text/plain Access-Control-Allow-Origin: http://www.example.com Access-Control-Allow-Credentials: true 25 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 26. Browser Support Native Server Support:  Chrome 4.0+  Use a CORS-aware  Firefox 3.5+ server  Add Access-Control-  Safari 4.0+ Allow-Origin header  IE 8+* 10+ to server config.  Opera 12+ http://caniuse.com/#search=CORS *partial via XDomainRequest 26 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 27. XMLHttpRequest Level 2 27 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 28. XMLHttpRequest Level 2 Improvements  XMLHttpRequest (XHR) made Ajax possible  Level 2 significantly enhances XMLHttpRequest • Progress events • Cross-origin XMLHttpRequest • Binary support  Specification: • http://www.w3.org/TR/XMLHttpRequest/ 28 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 29. Progress Events  In the past: inconsistently implemented across browsers e.g. readyState 3 (progress) never fires in IE XMLHttpRequest Level 2 adds progress events: • loadstart • progress • abort • error • load • loadend readyState property and readystatechange events retained for backward compatibility 29 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 30. Progress Events  Fields for: • The total amount of data to transfer • The amount that has already transferred (use new HTML5 progress element) • Whether the total is known JavaScript crossOriginRequest.upload.onprogress = function(e) { var total = e.total; var loaded = e.loaded; if (e.lengthComputable) { // do something with the progress information } } 30 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 31. Cross-Origin XMLHttpRequest JavaScript //from http://www.example.com var crossOriginRequest = new XMLHttpRequest(); crossOriginRequest.open("GET", "http://www.example.net/stockfeed", true); * Requires CORS-enabled server (to handle origin and Access Control headers) 31 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 32. Binary Data  Supports Blob and ArrayBuffer (aka Typed Array) objects  Good for for WebGL, programmable audio, etc.  Demo: http://www.html5rocks.com/en/tutorials/file/xhr2/ JavaScript //Sending a Typed Array of bytes var a = new Uint8Array([8,6,7,5,3,0,9]); varxhr = new XMLHttpRequest(); xhr.open("POST", "/data/", true) xhr.send(a.buffer); 32 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 33. Browser Support: XHR Level 2 Native  IE 8+ supports XDR  Chrome 2.0+  Server side  Firefox 3.5+ participation may be  Safari 4.0+ required (CORS)  Opera 12+ http://caniuse.com/#search=XMLHTTPRequest  IE 8+* 10+ *partial via XDomainRequest 33 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 34. WebSocket 34 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 35. If You Want to Build Web Apps for…  Financial trading  Social networking  Gaming  Gambling  System monitoring  RFID tracking  …WebSocket will be useful 35 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 36. Previous Approaches  Comet and Reverse Ajax  Based on HTTP  HTTP is stateless and half-duplex 36 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 37. Overhead  HTTP is stateless, results in HTTP header overhead  Example: • Type one character: ~1500 characters exchanged  Example: http://syntensity.com/static/espeak.html 37 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 38. HTTP Request Headers Client GET /PollingStock//PollingStock HTTP/1.1 Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://localhost:8080/PollingStock/ Cookie: showInheritedConstant=false; showInheritedProtectedConstant=false; showInheritedProperty=false; showInheritedProtectedProperty=false; showInheritedMethod=false; showInheritedProtectedMethod=false; showInheritedEvent=false; showInheritedStyle=false; showInheritedEffect=false; 38 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 39. HTTP Response Headers Server HTTP/1.x 200 OK X-Powered-By: Servlet/2.5 Server: Sun Java System Application Server 9.1_02 Content-Type: text/html;charset=UTF-8 Content-Length: 321 Date: Sat, 07 Nov 2009 00:32:46 GMT • Total overhead: 871 bytes (example) • Often 1.5K+ bytes (for example, cookie data) • Overhead is expensive! 39 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 40. Upload/Download Ratios  Most users have Internet connections where upload to download ratios are between 1:4 and 1:20 •Result: 500 byte HTTP request header request could take as long to upload as 10 kB of HTTP response data takes to download 40 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 41. Enter WebSocket  W3C API (Javascript)  IETF Protocol  Full-duplex (bi- directional), single socket  Shares port with existing HTTP content  Schemes: ws:// and wss:// 41 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 42. Using the WebSocket API JavaScript //Create new WebSocket var mySocket = new WebSocket("ws://www.WebSocket.org"); // Associate listeners mySocket.onopen = function(evt) { }; mySocket.onclose= function(evt) { alert("closed w/ status: " + evt.code}; }; mySocket.onmessage = function(evt) { alert("Received message: " + evt.data); }; mySocket.onerror = function(evt) { alert("Error); }; 42 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 43. Using the WebSocket API JavaScript // Sending data mySocket.send("WebSocket Rocks!"); // Close WebSocket mySocket.close(); 43 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 44. Checking for Feature Support JavaScript var status = document.getElementById("support"); if (window.WebSocket) { // or Modernizr.websocket status.innerHTML = "HTML5 WebSocket is supported"; } else { status.innerHTML = "HTML5 WebSocket is not supported"; } 44 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 45. WebSocket History  Originally added to HTML5 Spec as TCPConnection  Moved to its own specification 45 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 46. WebSocket Protocol History “draft-hixie-thewebsocketprotocol-xx” IETF Network Working Group Version Date Details -00 Jan. 9 2009 • Initial version -52 Oct. 23 2009 • Subprotocol concept introduced -76 May 6 2010 • Used in older browsers (FF4, etc.) “draft-ietf-hybi-thewebsocketprotocol-xx” (IETF HyBi Working Group) Version Date Details -01 Aug. 31 2010 • Added binary format -04 Jan. 11 2011 • Introduced data masking to address proxy server security issue • Introduced including protocol version number in handshake RFC 6455 Dec. 2011 • Final version http://tools.ietf.org/html/rfc6455 46 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 47. WebSocket Handshake 47 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 48. WebSocket Frames • Have a few header bytes • Text or binary data • Frames are maskedfrom client to server 48 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 49. WebSocket Frames Wireshark Trace of WebSocket Basics Lab Message (Client to Server) FIN bit, MASK bit, RSV bits, Op- payload mask payload Code length 81 85 CB 6E 9F 8E 83 0B F3 E2 A4 83 0B F3 E2 A4 XOR CB 6E 9F 8E CB -- -- -- -- -- 48 65 6C 6C 6F H ello 49 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 50. WebSocket Frames Wireshark Trace of WebSocket Basics Lab Message (Server to Client) FIN bit, MASK bit, RSV bits, Op- payload payload Code length 81 05 48 65 6C 6C 6F H e l l o 50 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 51. WebSocket Efficiency HTTP WebSocket Overhead 100s of bytes 2-6 bytes (typical) Latency New connection None: Use existing each time connection Latency Wait for next No waiting (polling) interval Latency None, if request No waiting (long polling) sent earlier + time to set up next request 51 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 52. Polling vs. WebSocket 52 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 53. WebSocket Latency Benchmark Using Comet Using WebSocket http://webtide.intalio.com/2011/09/cometd-2-4-0-websocket-benchmarks/ 53 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 54. Browser Support Native: Emulation: • Chrome 4+ • KaazingWebSocket • Safari 5+ Gateway • Firefox 4+ • socket.io • Opera 10.7+ • SockJS • Internet Explorer 10+ • web-socket.js (Flash) http://caniuse.com/#search=WebSocket 54 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 55. WebSocket Servers and Client Libraries  Kaazing  Misultin Client Libraries  Socket.io (node.js)  Cowboy  Web-socket-js (JavaScript)  Apache-websocket  YAWS  AS3 WebSocket (ActionScript)  Cramp  Juggernaut  .NET WebSocket client (.NET)  Nowjs  PHP Websocket  Anaida (.NET)  SockJS  websockify  WebSocket Sharp (.NET)  SuperWebSocket  ActiveMQ  Silverlight WebSocket client  Jetty  HornetMQ  Java WebSocket Client  Atmosphere  phpwebsocket  Arduino C++ WebSocket client  APE Project  Protocol::WebSocket  Ruby-web-socket  Xsockets  em-websocket  ZTWebSocket (Objective-C)  Orbited  Jwebsocket  Libwebsockets (C)  Atmosphere  WaterSprout Server  Autobahn  Pywebsocket  CouchDB  And more… 55 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 56. Extending WebSocket  Once you have WebSocket, you can extend client-server protocols to the web:  Chat: XMPP (Jabber), IRC  Pub/Sub (Stomp/AMQP)  VNC (RFB)  Any TCP-based protocol  Browser becomes a first-class network citizen  Real-world intermediaries can mess with traffic (best practice is to use WebSocket Secure) 56 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 57. WebSocket and (Dreaded) Proxy Servers http://www.infoq.com/articles/Web-Sockets-Proxy-Servers 57 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 58. ws:// and wss:// schemes 58 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 59. Traditional Architecture 59 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 60. WebSocket Architecture 100% Hipster 60 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 61. Quiz (Win a Book) Which has more trouble with an unencrypted (ws://) connection? 1. Transparent proxies 2. Explicit proxies 3. Squid proxies 4. Firewalls 61 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 62. Server Sent Events 62 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 63. Server-Sent Events  Standardizes sending a continuous stream of data from server to browser  Compatible with most setups using HTTP  EventSource API  Great for newsfeeds, one-way stream of data  SSE-specific features: • Automatic reconnection • Event IDs 63 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 64. SSE Architecture 64 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 65. Using the EventSource API JavaScript if (!!windows.EventSource) { // or Modernizr.eventsource var stream = new EventSource("http://example.com"); //Events stream.onopen = function() { log("open"); } stream.onmessage = function(evt) { log("message: " + evt.data); } stream.onerror = function(evt) { if (evt.eventPhase != EventSource.CLOSED) { log("error"); }}}; 65 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 66. Example: News Broadcast http://kaazing.me/ 66 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 67. Browser Support Native: Emulation: • Chrome 6+ • EventSource.js (Remy • Safari 5+ Sharp) • Firefox 6+ http://goo.gl/FyanG • Opera 10.6+ • KaazingWebSocket Gateway http://caniuse.com/#search=eventsource 67 Copyright © 2012 Kaazing Corporation. All Rights Reserved. ?
  • 68. SPDY Pronounce: ˈspēdē - 68 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 69. SPDY  Not an acronym (name shows how compression can help improve speed: SPeeDY)  New Application Layer Protocol to “make the web faster” • Reduce page load times by ~50% • Augments HTTP (Not a replacement) • Uses HTTP-like request-response setup 69 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 70. SPDY Features  HTTP header compression (85%-88% reduction)  Always over TLS  Next Protocol Negotiation (NPN)  Request prioritization  Server push  Multiplex logical HTTP (or WebSocket) 70 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 71. SPDY Advantages  Better than HTTP pipelining • Not on by default, difficult to deploy • Head of Line Blocking issues  Single TCP connection (works around connection limits per origin, less need for subdomains, Data URIs 71 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 72. Why use TLS/port 443?  Encrypted tunnel allows traversal of intermediaries  Less overhead than originally thought  You need secure communication anyway  Using standard, open ports has a big advantage "We want some chance of getting this protocol out in our live time” —Roberto Peon (Google) 72 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 73. SPDY in Chrome  Default (95% of the time)  WebSocket over SPDY, use command line switch in Google Chrome: --enable-websocket-over-spdy chrome://net-internals/#spdy 73 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 74. SPDY in Firefox  Since version 11 preference in about:config: network.http.spdy.enabled  Default in version 13 74 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 75. HTTP Strict Transport Security  Forces browser to use HTTPS • Not simply HTTPredirectHTTPS • Address rewritten before request  Enable with Strict-Transport-Security header  Browser support: FF4+, Chrome  References: • mikewest.org/2011/10/http-strict-transport-security-and-you • tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-02 75 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 76. Questions? • E-mail: peter.lubbers@kaazing.com • Twitter: @peterlubbers • LinkedIn: Peter Lubbers 76 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 77. Announcing the HTML5 Code Labs  Series of three Code Labs: • March 7 • April 10 • May 5 (HTML Cinco!)  In conjunction with GTUGSF  Sign up: http://GTUGsf.com/HTML5 77 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 78. Buy the Book! • Pro HTML5 Programming (Apress, 2011) • 50% off e-book coupon code: 50OFFHTML5 http://goo.gl/Dzq4A 78 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 79. Additional Resources  Scheme host port blog (Adam Barth): http://www.schemehostport.com/  SPDY Essentials (Google Tech Talk): http://goo.gl/IcVdF  Breaking the Cross Domain Barrier (Alex Slexton): http://goo.gl/IcVdF  SPDY whitepaper: http://dev.chromium.org/spdy/spdy-whitepaper  XHR Level 2 Article (Eric Bidelman): http://www.html5rocks.com/en/tutorials/file/xhr2/  HTML5 Weekly: http://html5weekly.com/  The Web Ahead Podcasts: http://5by5.tv/webahead/ 79 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 80. Get Trained!  Proven, practical worldwide HTML5 Training (from experts, not just trainers): • E-mail us: training@kaazing.com • Web site: http://kaazing.com/training/ 80 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 81. - 81 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  • 82. Quiz Answers  Origins 1 and 6 are the same  Transparent Proxies 82 Copyright © 2012 Kaazing Corporation. All Rights Reserved.

Editor's Notes

  1. When sending a message, data (Hello World) is like a letter in an envelope. Then put target on envelope – this needs to be the target origin and look for it to be available. Your origin source is stamped on it – so it can’t be spoofed.
  2. Verify the source origin of every message e.g. use a whitelistTreat message data with caution (even from a trusted source): Validate length Check extracted values (format, range)
  3. One common way to fetch data from another origin is JSONP. JSONP involves creating a script tag with the URL of a JSON resource. The URL has a query parameter containing the name of a function to invoke when the script loads. It is up to the remote server to wrap the JSON data with a call to the named function. This has serious security implications! When you use JSONP, you must completely trust the service providing the data. A malicious script could take over your application. With XHR and CORS, you receive data instead of code, which you can parse safely. It’s far safer than evaluating external input.”
  4. Referer is still there but can be a complete path, whereas the origin is just the scheme/origin/port
  5. Progress bar – can check how much of something is loaded and perform math calculation (like %)
  6. Note: The CORS specification dictates that, for sensitive actions—for example, a request with credentials, or a request other than GET or POST—an OPTIONS preflight request must be sent to the server by the browser to see whether the action is supported
  7. Browsers that support new binary APIs such as Typed Array (which is necessary for WebGL and programmable audio) may be able to send binary data with XMLHttpRequest. The XMLHttpRequest Level 2 specification includes support for calling the send() method with Blob and ArrayBuffer (aka Typed Array) objects.This makes an HTTP POST request with a binary content body. The content-length is 7, and the body contains the bytes 8,6,7,5,3,0,9. XMLHttpRequest Level 2 also exposes binary response data. Setting the responseType attribute to “text”, “document”, “arraybuffer,” or “blob” controls the type of object returned by the response property. To see the raw bytes contained by the HTTP response body, set the responseType to “arraybuffer” or “blob”.
  8. Note:
  9. Here is a graphical view of the data which shows the dramatic reduction in overhead relative to Ajax or Comet for any number of clients.
  10. Run by the Jetty folks on their optimized Comet server. Emulated a chatroom on EC2. Left: Comet implementation, 2-4ms latency for 5-50K emulated clients @ 10Kmessages/sec. Starts climbing linearly from there up to around 180ms @ 50K messages/sec, except for the 50K client case (hits an internal network limit @ Amazon.)Right: WebSocket implementation of same. 2-4ms latency for all cases _except_ a new 200K client setting that looked like it would start hitting the same internal network limit. (4x as many client, still 5-6 msec.)