Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
HTML5 Real-Time and                                                            Connectivity                               ...
About @peterlubbers       Sr. Director Technical Communication        Kaazing (we’re hiring)       Author, Pro HTML5 Pro...
Agenda     Web Origin Concept     Cross Document Messaging                                                  #sfhtml5    ...
HTML5 Feature Areas           "HTML5 should not be considered as a whole.         You should cherry-pick the technology th...
HTML5 Feature Areas5               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Tonight’s Focus6                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
HTML5 Paves the Cow Paths        HTML5 takes a pragmatic approach, fixing         real-world problems        Especially ...
Web Origins8                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.   Credit: http://singleorigin.com....
Web Origin Concept       Web Origin Concept RFC 6454:        http://www.ietf.org/rfc/rfc6454.txt       An Origin is a su...
Same-Origin Policy     “Generally speaking, documents retrieved from distinct      origins are isolated from each other” –...
Origin Quiz (Win a Book)     Which URLs have the same Origin?       1.   http://www.example.com/index.html       2.   http...
Cross Document Messaging12               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Cross Document Messaging        Enables secure cross-origin communication         across iframes, tabs, and windows     ...
PostMessage Architecture14               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Using PostMessage     Sending a message     JavaScript           myFrame.contentWindow.postMessage           (Hello, world...
Using PostMessage      Processing a message     JavaScript        window.addEventListener("message", messageHandler,true);...
Handlewith Care      Warning: “Use of this API requires extra care to       protect users from hostile entities abusing  ...
Using a Whitelist     JavaScript        varallowedOrigins = ["http://portal.example.com/",        "http://games.example.co...
Browser Support     Native                                        Emulation      Chrome 2.0+                             ...
CORS                                                         enable-cors.org20          Copyright © 2012 Kaazing Corporati...
Working with Multiple Origins        JSON with Padding (JSONP)         • JSON data in executable Javascript wrapper      ...
Cross-Origin Requests        Have an Originheader         •   Contains the request’s origin         •   Produced by the b...
CORS vs. Same Origin23                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 (...
Access Control Headers (Server Response)     HTTP      HTTP/1.1 201 Created      Transfer-Encoding: chunked      Server: K...
Browser Support      Native                                       Server Support:       Chrome 4.0+                      ...
XMLHttpRequest Level 227               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
XMLHttpRequest Level 2 Improvements        XMLHttpRequest (XHR) made Ajax possible        Level 2 significantly enhances...
Progress Events      In the past: inconsistently                                 implemented across browsers       e.g. r...
Progress Events       Fields for:            • The total amount of data to transfer            • The amount that has alre...
Cross-Origin XMLHttpRequest     JavaScript        //from http://www.example.com        var crossOriginRequest = new XMLHtt...
Binary Data          Supports Blob and ArrayBuffer (aka Typed Array) objects          Good for for WebGL, programmable a...
Browser Support: XHR Level 2       Native                                                IE 8+ supports XDR        Chrom...
WebSocket34               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
If You Want to Build Web Apps for…        Financial trading        Social networking        Gaming        Gambling    ...
Previous Approaches        Comet and Reverse Ajax        Based on HTTP        HTTP is stateless         and half-duplex...
Overhead        HTTP is stateless, results in HTTP header overhead        Example:          • Type one character: ~1500 ...
HTTP Request Headers     Client        GET /PollingStock//PollingStock HTTP/1.1        Host: localhost:8080        User-Ag...
HTTP Response Headers     Server        HTTP/1.x 200 OK        X-Powered-By: Servlet/2.5        Server: Sun Java System Ap...
Upload/Download Ratios      Most users have Internet connections where      upload to download ratios are between 1:4    ...
Enter WebSocket      W3C API (Javascript)      IETF Protocol      Full-duplex (bi-       directional), single       soc...
Using the WebSocket API     JavaScript        //Create new WebSocket        var mySocket = new WebSocket("ws://www.WebSock...
Using the WebSocket API     JavaScript        // Sending data        mySocket.send("WebSocket Rocks!");        // Close We...
Checking for Feature Support     JavaScript        var status = document.getElementById("support");        if (window.WebS...
WebSocket History        Originally added to HTML5 Spec as         TCPConnection        Moved to its         own specifi...
WebSocket Protocol History     “draft-hixie-thewebsocketprotocol-xx” IETF Network Working Group     Version        Date   ...
WebSocket Handshake47              Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Frames      •   Have a few header bytes      •   Text or binary data      •   Frames are maskedfrom client to se...
WebSocket Frames     Wireshark Trace of WebSocket Basics Lab Message (Client to Server)                                   ...
WebSocket Frames     Wireshark Trace of WebSocket Basics Lab Message (Server to Client)                                   ...
WebSocket Efficiency                       HTTP                                         WebSocket     Overhead          10...
Polling vs. WebSocket52                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Latency Benchmark           Using Comet                                         Using WebSocket               ht...
Browser Support     Native:                 Emulation:     • Chrome 4+             • KaazingWebSocket     • Safari 5+     ...
WebSocket Servers and Client Libraries        Kaazing                                Misultin                           ...
Extending WebSocket        Once you have WebSocket, you can extend         client-server protocols to the web:          ...
WebSocket and (Dreaded) Proxy Servers                                                 http://www.infoq.com/articles/Web-So...
ws:// and wss:// schemes58               Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Traditional Architecture59                 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
WebSocket Architecture     100% Hipster60                  Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Quiz (Win a Book)     Which has more trouble with an unencrypted        (ws://) connection?     1. Transparent proxies    ...
Server Sent Events62                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Server-Sent Events         Standardizes sending a continuous          stream of data from server to browser         Comp...
SSE Architecture64                Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Using the EventSource API     JavaScript         if (!!windows.EventSource) { // or         Modernizr.eventsource         ...
Example: News Broadcast                            http://kaazing.me/66               Copyright © 2012 Kaazing Corporation...
Browser Support     Native:                                    Emulation:     • Chrome 6+                                •...
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 La...
SPDY Features        HTTP header compression (85%-88% reduction)        Always over TLS        Next Protocol Negotiatio...
SPDY Advantages        Better than HTTP pipelining          • Not on by default, difficult to deploy          • Head of L...
Why use TLS/port 443?      Encrypted tunnel allows traversal of       intermediaries      Less overhead than originally ...
SPDY in Chrome        Default (95% of the time)        WebSocket over SPDY, use command line         switch in Google Ch...
SPDY in Firefox        Since version 11 preference in about:config:         network.http.spdy.enabled        Default in ...
HTTP Strict Transport Security        Forces browser to use HTTPS         • Not simply HTTPredirectHTTPS         • Addr...
Questions?     •   E-mail: peter.lubbers@kaazing.com     •   Twitter: @peterlubbers     •   LinkedIn: Peter Lubbers76     ...
Announcing the HTML5 Code Labs        Series of three Code Labs:          • March 7          • April 10          • May 5 ...
Buy the Book!     •   Pro HTML5 Programming (Apress, 2011)     •   50% off e-book coupon code:         50OFFHTML5         ...
Additional Resources        Scheme host port blog (Adam Barth):         http://www.schemehostport.com/        SPDY Essen...
Get Trained!        Proven, practical worldwide HTML5 Training         (from experts, not just trainers):         • E-mai...
-81   Copyright © 2012 Kaazing Corporation. All Rights Reserved.
Quiz Answers        Origins 1 and 6 are the same        Transparent Proxies82                  Copyright © 2012 Kaazing ...
Upcoming SlideShare
Loading in …5
×

HTML5 Real-Time and Connectivity

30,029 views

Published on

These are the slides from my "HTML5 Real-TIme and Connectivity" presentation at the San Francisco HTML5 User Group (http://sfhtml5.org). The presentation covers:
Web Origin
Cross Document Messaging (PostMessage)
CORS
XHR Level2
WebSocket
Server-Sent Events (EventSource)
SPDY

Published in: Technology
  • Professional bull rider Travis Rowe is convinced that the "Demolisher" Betting System is so good, it will eventually force the sportsbook to shut down his wagers to a minimum! ♥♥♥ http://t.cn/A6zP2GDT
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

HTML5 Real-Time and Connectivity

  1. 1. HTML5 Real-Time and Connectivity @peterlubbers Kaazing Creators of WebSocket WebSocket Gateway High Performance HTML5 Training1 Copyright © 2012 Kaazing Corporation. All Rights Reserved. Illustration by Will Phillips Jr.
  2. 2. About @peterlubbers  Sr. Director Technical Communication Kaazing (we’re hiring)  Author, Pro HTML5 Programming  HTML5… it’s how I roll2 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  3. 3. Agenda  Web Origin Concept  Cross Document Messaging #sfhtml5 @peterlubbers  CORS XMLHttpRequest Level 2 WebSocket  Server-Sent Events  SPDY3 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  4. 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. 5. HTML5 Feature Areas5 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  6. 6. Tonight’s Focus6 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  7. 7. HTML5 Paves the Cow Paths  HTML5 takes a pragmatic approach, fixing real-world problems  Especially true for connectivity features7 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  8. 8. Web Origins8 Copyright © 2012 Kaazing Corporation. All Rights Reserved. Credit: http://singleorigin.com.au/
  9. 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, 4439 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  10. 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 apps10 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  11. 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.com11 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  12. 12. Cross Document Messaging12 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  13. 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. 14. PostMessage Architecture14 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  15. 15. Using PostMessage Sending a message JavaScript myFrame.contentWindow.postMessage (Hello, world, http://www.example.com/);  myFrame.contentWindowdestination  http://www.example.comtarget origin15 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  16. 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. 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. 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. 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=postmessage19 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  20. 20. CORS enable-cors.org20 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  21. 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 Salim21 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  22. 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. 23. CORS vs. Same Origin23 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  24. 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-cache24 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  25. 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: true25 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  26. 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 XDomainRequest26 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  27. 27. XMLHttpRequest Level 227 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  28. 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. 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 compatibility29 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  30. 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. 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. 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. 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 XDomainRequest33 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  34. 34. WebSocket34 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  35. 35. If You Want to Build Web Apps for…  Financial trading  Social networking  Gaming  Gambling  System monitoring  RFID tracking  …WebSocket will be useful35 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  36. 36. Previous Approaches  Comet and Reverse Ajax  Based on HTTP  HTTP is stateless and half-duplex36 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  37. 37. Overhead  HTTP is stateless, results in HTTP header overhead  Example: • Type one character: ~1500 characters exchanged  Example: http://syntensity.com/static/espeak.html37 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  38. 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. 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. 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 download40 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  41. 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. 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. 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. 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. 45. WebSocket History  Originally added to HTML5 Spec as TCPConnection  Moved to its own specification45 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  46. 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/rfc645546 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  47. 47. WebSocket Handshake47 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  48. 48. WebSocket Frames • Have a few header bytes • Text or binary data • Frames are maskedfrom client to server48 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  49. 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 ello49 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  50. 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 o50 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  51. 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 request51 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  52. 52. Polling vs. WebSocket52 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  53. 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. 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=WebSocket54 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  55. 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. 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. 57. WebSocket and (Dreaded) Proxy Servers http://www.infoq.com/articles/Web-Sockets-Proxy-Servers57 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  58. 58. ws:// and wss:// schemes58 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  59. 59. Traditional Architecture59 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  60. 60. WebSocket Architecture 100% Hipster60 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  61. 61. Quiz (Win a Book) Which has more trouble with an unencrypted (ws://) connection? 1. Transparent proxies 2. Explicit proxies 3. Squid proxies 4. Firewalls61 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  62. 62. Server Sent Events62 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  63. 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 IDs63 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  64. 64. SSE Architecture64 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  65. 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. 66. Example: News Broadcast http://kaazing.me/66 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  67. 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=eventsource67 Copyright © 2012 Kaazing Corporation. All Rights Reserved. ?
  68. 68. SPDY Pronounce: ˈspēdē -68 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  69. 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 setup69 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  70. 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. 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 URIs71 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  72. 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. 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/#spdy73 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  74. 74. SPDY in Firefox  Since version 11 preference in about:config: network.http.spdy.enabled  Default in version 1374 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  75. 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-0275 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  76. 76. Questions? • E-mail: peter.lubbers@kaazing.com • Twitter: @peterlubbers • LinkedIn: Peter Lubbers76 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  77. 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/HTML577 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  78. 78. Buy the Book! • Pro HTML5 Programming (Apress, 2011) • 50% off e-book coupon code: 50OFFHTML5 http://goo.gl/Dzq4A78 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  79. 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. 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. -81 Copyright © 2012 Kaazing Corporation. All Rights Reserved.
  82. 82. Quiz Answers  Origins 1 and 6 are the same  Transparent Proxies82 Copyright © 2012 Kaazing Corporation. All Rights Reserved.

×