HTML5 Web Workers-unleashed

11,065 views

Published on

3 Comments
12 Likes
Statistics
Notes
  • Great slideshow. thanks!
    4D Planning
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Chris:
    You can add a button to pause the execution by sending a message to the worker

    document.getElementById('startButton').onclick = function () {
    worker.postMessage('pause');
    }

    In the worker you then add a message handler:
    function messageHandler(e) {
    if (e.data == 'pause') {
    //pause the worker
    }
    }

    Note: you can also terminate a worker with
    worker.terminate();
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • i have a question for web workers. Let’s have a worker that calculates prime numbers. When a prime number is calculated the worker post this number to the page and the page show this to the screen. How can i have a button to pause the process? This will not work ... ... ... onmessage=function(e) { if (e.data==’pause’) pauseproccess=true; } ... ... ... while (!pauseproccess) { //calculate prime numbers }
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
11,065
On SlideShare
0
From Embeds
0
Number of Embeds
20
Actions
Shares
0
Downloads
424
Comments
3
Likes
12
Embeds 0
No embeds

No notes for slide
  • Google Chrome – every tab is its own program (not one tab within a program). So if one tab goes down, the whole app doesn't crash.
  • 150 ms (TCP round trip to set up the connection plus a packet for the message)50 ms (just the packet for the message)
  • The following steps are shown in the diagram: A user navigates to a location-aware application in the browser.The application web page loads and requests coordinates from the browser by making a Geolocation function call. The browser intercepts this and requests user permission. Let's assume that the permission is granted.The browser retrieves coordinate information from the device it is running on. For example, the IP address, Wi-Fi, or GPS coordinates. This is an internal function of the browser.The browser sends these coordinates to a trusted external location service, which returns a detailed location that can now be sent back to the host of the HTML5 Geolocation application.
  • The successCallback function parameter tells the browser which function you want called when the location data is made available. This is important because operations such as fetching location data may take a long time to complete. No user wants the browser to be locked up while the location is retrieved, and no developer wants his program to pause indefinitely—especially because fetching the location data will often be waiting on a user to grant permission. The successCallback is where you will receive the actual location information and act on it.However, as in most programming scenarios, it is good to plan for failure cases. It is quite possible that the request for location information may not complete for reasons beyond your control, and for those cases you will want to provide an errorCallback function that can present the user with an explanation, or perhaps make an attempt to try again. While optional, it is recommended that you provide one.Finally, an options object can be provided to the HTML5 Geolocation service to fine-tune the way it gathers data. This is an optional parameter that we will examine later.
  • The timeout value deals with the duration needed to calculate the location value, while maximumAge refers to the frequency of the location calculation. If any single calculation takes longer than the timeout value, an error is triggered. However, if the browser does not have an up-to-date location value that is younger than maximumAge, it must refetch another value. Special values apply here: setting the maximumAge to “0” requires the value to always be re-fetched, while setting it to Infinity means it should never be refetched.
  • This sample works by using the watchPosition() capability we discussed in the last section. Every time a new position is sent to us, we will compare it to the last known position and calculate the distance traveled. This is accomplished using a well-known calculation known as the Haversine formula, which allows us to calculate distance between two longitude and latitude positions on a sphere.
  • High-message volume, small message size scenario where long-polling is potentially worse than polling.
  • WebSocket is text-only
  • HTTP used for handshake onlyOperates over a single socketTraverses firewalls and routers seamlesslyAllows authorized cross-site communicationCookie-based authenticationExisting HTTP load balancersNavigates proxies using HTTP CONNECT, same technique as https, but without the encryption
  • Text type requires high-order bit setBinary type requires high-order bit _not_ setThere is no defined maximum size. However, the protocol allows either side (browser or server) to terminate the connection if it cannot receive a large frame. So far, the definition of too large is left up to the implementation.If the user agent is faced with content that is too large to behandled appropriately, then it must fail the Web Socket connection.There is probably a practical maximum, but we have not discovered it as far as I know.You can't have four gigabytes of data in JavaScript, so the practical max is <4GB for the JavaScript implementation.
  • 150 ms (TCP round trip to set up the connection plus a packet for the message)50 ms (just the packet for the message)
  • 150 ms (TCP round trip to set up the connection plus a packet for the message)50 ms (just the packet for the message)
  • Text type requires high-order bit setBinary type requires high-order bit _not_ setThere is no defined maximum size. However, the protocol allows either side (browser or server) to terminate the connection if it cannot receive a large frame. So far, the definition of too large is left up to the implementation.If the user agent is faced with content that is too large to behandled appropriately, then it must fail the Web Socket connection.There is probably a practical maximum, but we have not discovered it as far as I know.You can't have four gigabytes of data in JavaScript, so the practical max is <4GB for the JavaScript implementation.
  • HTML5 Web Workers-unleashed

    1. 1. Peter Lubbers <br />Kaazing<br />#dcode<br />HTML5WebSockets,Web Workers,andGeolocation<br />Unleashed! <br />
    2. 2. About Peter Lubbers<br /><ul><li>Director of Documentation and Training, Kaazing (The HTML5 WebSocket Company)
    3. 3. Co-Founder San Francisco HTML5 User Grouphttp://www.sfhtml5.org/
    4. 4. Co-author Pro HTML5 Programming
    5. 5. Ultra Distance Runner
    6. 6. Twitter: @peterlubbers</li></ul>Copyright © 2010 - Kaazing Corporation. All rights reserved.<br />
    7. 7. Agenda<br /><ul><li>About HTML5
    8. 8. HTML5 Web Workers
    9. 9. HTML5 Geolocation
    10. 10. HTML5 Web Sockets
    11. 11. Q&A</li></ul> And…the first ones to answer the quiz questions win a free book!<br />Copyright © 2010 - Kaazing Corporation. All rights reserved.<br />
    12. 12. AboutHTML5<br />© 2009 – Kaazing Corporation<br />
    13. 13. HTML5 Paves the Cow Paths<br /><ul><li>Degrade gracefully (Evolution not revolution)
    14. 14. Don't reinvent the wheel (or at least make a better one!)</li></ul>Copyright © 2010 - Kaazing Corporation. All rights reserved.<br />
    15. 15. HTML5: Simple is Better<br /><ul><li>Simplify wherever possible
    16. 16. Examples:
    17. 17. Native browser ability instead of complex JavaScript code
    18. 18. New doctype
    19. 19. Character set
    20. 20. HTML5 APIs
    21. 21. As they say in Holland: “So simple, a child can do the laundry!”</li></ul>Copyright © 2010 - Kaazing Corporation. All rights reserved.<br />
    22. 22. HTML5 : A Plugin-Free Paradigm<br /><ul><li>HTML5 provides native support for many features that were only possible with plugins or complex hacks
    23. 23. Problems with plugins:
    24. 24. May not be installed
    25. 25. Can be disabled
    26. 26. Are a separate attack vector
    27. 27. Are difficult to integrate with the rest of an HTML document (plugin boundaries, clipping, and transparency issues)</li></ul>“Whenever a Mac crashes more often than not it’s because of Flash.”<br />--Steve Jobs<br />Copyright © 2010 - Kaazing Corporation. All rights reserved.<br />
    28. 28.
    29. 29. Just Kidding!<br />Copyright © 2010 - Kaazing Corporation. All rights reserved.<br />
    30. 30. Is This HTML5?<br /><ul><li>Many pieces of the HTML5 effort were originally part of the HTML5 specification
    31. 31. Moved to a separate standards document to keep the specification focused
    32. 32. Industry still refers to the original set of features, including Web Sockets, as "HTML5“
    33. 33. See: http://www.whatwg.org/specs/web-apps/current-work/multipage/introduction.html#is-this-html5?</li></ul>Copyright © 2010 - Kaazing Corporation. All rights reserved.<br />
    34. 34. HTML5 Web Workers<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    35. 35. HTML5 Web Workers<br /><ul><li>Without Web Workers:
    36. 36. Long-running JavaScript tasks can block other JavaScript on the page
    37. 37. JavaScript can cause some browser UIs to hang
    38. 38. With Web Workers:
    39. 39. Background processing capabilities to web applications can be added
    40. 40. Parallel operations can run concurrently</li></ul>Copyright © 2010 - Kaazing Corporation. All rights reserved.<br />
    41. 41. HTML5 Web Workers<br /><ul><li>Web Workers are used for
    42. 42. Background number-crunchers
    43. 43. Background notification from server to a local database
    44. 44. Background price updates from server
    45. 45. Search queries
    46. 46. Graceful degradation? Easy!</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    47. 47. Demo<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    48. 48. Using the Web Workers API<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    49. 49. HTML5 Web Workers<br /><ul><li>Cannot access the web page’s window object (window.document)
    50. 50. No direct access to the web page and the DOM API
    51. 51. Can use the full JavaScript timing API, typically found on the global window
    52. 52. Although HTML5 Web Workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsive</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    53. 53. HTML5 Web Workers API<br /><ul><li>Create an HTML5 Web Worker object and pass in a JavaScript file to be executed
    54. 54. Use Cross Document Messaging API (PostMessage)
    55. 55. On the web page:
    56. 56. Set up an (asynchronous) event listener to listen to incoming messages and errors from the worker
    57. 57. call postMessage to pass data to a worker
    58. 58. On the web page:
    59. 59. Set up an (asynchronous) event listener to listen to incoming messages and errors from the page
    60. 60. call postMessage to pass data to the page</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    61. 61. JavaScript<br />//Check if Web Workers are supported<br />if (typeof(Worker) !== "undefined") {<br /> document.getElementById("support").innerHTML = “Your browser supports HTML5 Web Workers";<br />}<br />//Create a new worker<br />//The URL for the JavaScript file can be a relative or //absolute URL with the same origin <br />//(the same scheme, host, and port) as the main page<br />worker = new Worker("echoWorker.js");<br />//to load additional JavaScript<br />importScripts("helper.js, "anotherHelper.js");<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    62. 62. JavaScript<br />//Main Page<br />worker.postMessage("Here's a message for you");<br />//Add event listener<br />worker.addEventListener("message", messageHandler, true);<br />//Process incoming messages<br />function messageHandler(e) {<br /> // process message from worker<br />}<br />//Handle errors<br />worker.addEventListener("error", errorHandler, true);<br />//Stop worker<br />worker.terminate();<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    63. 63. JavaScript<br />//Worker<br />function messageHandler(e) {<br /> postMessage("worker says: " + e.data + " too");<br />}<br />addEventListener("message", messageHandler, true);<br />//Using a Web Worker within a Web Worker <br />var subWorker = new Worker("subWorker.js");<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    64. 64. Browser Support<br /><ul><li>Chrome 4.0+
    65. 65. Firefox 3.5+
    66. 66. Safari 4.0+
    67. 67. Opera 10.6+</li></ul>* May need to be served up from a server (origin security)<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    68. 68. HTML5 Geolocation<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    69. 69. Using Geolocation<br /><ul><li>Allows users to share their location for location-aware services
    70. 70. Show user's position on map
    71. 71. Tag content (photos/sound/video)
    72. 72. Turn-by-turn navigation
    73. 73. Alert users of nearby points of interest
    74. 74. Social networking</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    75. 75. Demo<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    76. 76. Geolocation Architecture<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    77. 77. Location Data<br /><ul><li>Location information consists of a pair of latitude and longitude coordinates and accuracy information
    78. 78. Latitude is the numerical value indicating distance north or south of the equator
    79. 79. Longitude is the numerical value indicating distance east or west of Greenwich, England
    80. 80. For Example, Lake Tahoe:Latitude: 39.17222, Longitude: -120.13778</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    81. 81. Location Metadata<br /><ul><li>Depending on the device, additional meta data can be provided:
    82. 82. Altitude
    83. 83. altitudeAccuracy
    84. 84. Heading
    85. 85. Speed
    86. 86. If this additional metadata is not available it will be returned as a null value</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    87. 87. Sources of Location Data<br /><ul><li>A device can use any of the following sources:
    88. 88. IP address
    89. 89. Coordinate triangulation
    90. 90. Global Positioning System (GPS)
    91. 91. Wi-Fi with MAC addresses from RFID, Wi-Fi, and Bluetooth
    92. 92. GSM or CDMA cell phone IDs
    93. 93. User defined</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    94. 94. Location Source Pros & Cons<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    95. 95. Privacy<br /><ul><li>HTML5 Geolocation specification mandates that a mechanism is provided to protect the user's privacy
    96. 96. Location information should not be made available unless the application’s users grant their express permission
    97. 97. Clear privacy practices with respect to collected location data are recommended (how long data is stored, how it is encrypted, how data is shared)</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    98. 98. Sharing a Location<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    99. 99. Location Sharing Example<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    100. 100. Recommendations and Reality<br /><ul><li>Geolocation privacy study from UC Berkeley:http://bit.ly/aS9oqf</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    101. 101. Using the Geolocation API<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    102. 102. JavaScript<br />//Checking for browser support:<br />if(navigator.geolocation) {<br /> document.getElementById("support").innerHTML = "HTML5 Geolocation is supported.";<br /> } else {<br /> document.getElementById("support").innerHTML = "HTML5 Geolocation is not supported.";<br /> }<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    103. 103. © 2009 – Kaazing Corporation<br />Quiz Question: <br /> What are the names of the two main Geolocation API calls?<br />
    104. 104. Types of Position Requests<br /><ul><li>There are two types of position requests:</li></ul>One-shot position request(getCurrentPosition)<br />Repeated position updates(watchPosition)<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    105. 105. JavaScript<br />//One shot request<br />void getCurrentPosition( in PositionCallback successCallback, in optional PositionErrorCallback errorCallback, in optional PositionOptions options);<br />//Access user’s position<br />navigator.geolocation.getCurrentPosition( updateLocation, handleLocationError);<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    106. 106. JavaScript<br />//Update the UI<br />function updateLocation(position) {<br /> var latitude = position.coords.latitude;<br /> var longitude = position.coords.longitude;<br /> var accuracy = position.coords.accuracy;<br /> <br /> document.getElementById("latitude").innerHTML = latitude;<br /> document.getElementById("longitude").innerHTML = longitude;<br /> document.getElementById(“accuracy”).innerHTML = “This location is accurate within “ + accuracy + “ meters.”<br />}<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    107. 107. Optional Request Attributes<br /><ul><li>enableHighAccuracy—Request the HTML5 Geolocation service to use a higher accuracy-detection mode if available (only supports true or false)
    108. 108. Timeout—tells the browser the maximum amount of time it is allowed to calculate the current location
    109. 109. maximumAge—indicates how old a location value can be before the browser must attempt to recalculate (default is zero, meaning that the browser must attempt to recalculate a value immediately.</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    110. 110. Geolocation Error Codes<br /><ul><li>UNKNOWN_ERROR (code 0)An error occurred that is not covered by the other error codes
    111. 111. PERMISSION_DENIED (code 1) The user chose not to let the browser have access to the location information
    112. 112. POSITION_UNAVAILABLE (code 2)The technique used to determine the user’s location was attempted, but failed
    113. 113. TIMEOUT (code 3)The timeout value was exceeded</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    114. 114. JavaScript<br />//Repeated position updates<br />var watchId =navigator.geolocation.watchPosition( updateLocation, handleLocationError);<br />// do something with the location updates!<br />// ...<br /> <br />// Stop receiving location updates<br />navigator.geolocation.clearWatch(watchId);<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    115. 115. Example Geolocation App<br />watchPosition()<br />New Location<br />Haversine formula,calculate distance between two longitude and latitude positions on a sphere<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    116. 116. Google Map Integration<br /><ul><li>Coordinates are not easy to decipher, easier to see on a map
    117. 117. Google built support for HTML5 Geolocation into its user interface (Show My Location button) </li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    118. 118. JavaScript<br />//Show coordinates on a Google Map<br />// Create a Google  Map<br />//See Google API for more detail<br />var map = new google.maps.Map2(document.getElementById("map"));<br /> <br />function updateLocation(position) {<br /> //pass the position to the Google Map and center it<br /> map.setCenter(new google.maps.LatLng( position.coords.latitude, position.coords.longitude, 13); // zoom level<br />}<br /> <br />navigator.geolocation.getCurrentPosition( updateLocation, handleLocationError);<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    119. 119. Browser Support<br /><ul><li>Firefox 3.5
    120. 120. Safari 5.0
    121. 121. Chrome 5.0
    122. 122. Opera 10.6</li></ul>* Also possible through Gears<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    123. 123. HTML5 WebSocket<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    124. 124. Quiz Question: <br /> What do WebSockets and model trains have in common?<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    125. 125. Using WebSocket<br /><ul><li>Today’s Web applications demand reliable, real-time communications with near-zero latency
    126. 126. Not just broadcast, but bi-directional communication
    127. 127. Examples:
    128. 128. Financial applications
    129. 129. Social networking applications
    130. 130. Online games
    131. 131. Smart power grid</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    132. 132. Demo<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    133. 133. About HTTP<br /><ul><li>HTTP is half-duplex (traffic flows in only one direction at a time)
    134. 134. Header information is sent with each HTTP request and response, which can be an unnecessary overhead</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    135. 135. About Ajax and Comet<br /><ul><li>Great toilet cleaners…
    136. 136. Ajax (Asynchronous JavaScript and XML) is used to build highly interactive Web apps
    137. 137. Content can change without loading the entire page
    138. 138. User-perceived low latency
    139. 139. “Real-time” often achieved through polling and long-polling
    140. 140. Comet lack of a standard implementation
    141. 141. Comet adds lots of complexity</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    142. 142. Comet Polling Under the Covers<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    143. 143. HTTP Request Headers<br />GET /PollingStock//PollingStock HTTP/1.1<br />Host: localhost:8080<br />User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5<br />Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8<br />Accept-Language: en-us<br />Accept-Encoding: gzip,deflate<br />Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7<br />Keep-Alive: 300<br />Connection: keep-alive<br />Referer: http://localhost:8080/PollingStock/<br />Cookie: showInheritedConstant=false; showInheritedProtectedConstant=false; showInheritedProperty=false; showInheritedProtectedProperty=false; showInheritedMethod=false; showInheritedProtectedMethod=false; showInheritedEvent=false; showInheritedStyle=false; showInheritedEffect=false;<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    144. 144. HTTP Response Headers<br />HTTP/1.x 200 OK<br />X-Powered-By: Servlet/2.5<br />Server: Sun Java System Application Server 9.1_02<br />Content-Type: text/html;charset=UTF-8<br />Content-Length: 321<br />Date: Sat, 07 Nov 2009 00:32:46 GMT<br /><ul><li>Total (unnecessary) HTTP request and response header information overhead: 871 bytes (example)
    145. 145. Overhead can be as much as 2000 bytes
    146. 146. Does not scale!</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    147. 147. HTTP Header Traffic Analysis<br /><ul><li>Example network throughput for HTTP request and response headers associated with polling
    148. 148. Use case A: 1,000 clients polling every second:
    149. 149. Network throughput is (871 x 1,000) = 871,000 bytes = 6,968,000 bits per second (~6.6 Mbps)
    150. 150. Use case B: 10,000 clients polling every second:
    151. 151. Network throughput is (871 x 10,000) = 8,710,000 bytes = 69,680,000 bits per second (~66 Mbps)
    152. 152. Use case C: 100,000 clients polling every second:
    153. 153. Network throughput is (871 x 100,000) = 87,100,000 bytes = 696,800,000 bits per second (~665 Mbps)</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    154. 154. Comet: Headache 2.0<br />Use Comet to spellCOMplExiTy…<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    155. 155. HTML5 WebSocket<br /><ul><li>W3C API and IETF Protocol
    156. 156. Full-duplex, single socket
    157. 157. Enables web pages to communicate with a remote host
    158. 158. Traverses firewalls, proxies, and routers seamlessly
    159. 159. Leverages Cross-Origin Resource Sharing (CORS)
    160. 160. Share port with existing HTTP content
    161. 161. Dramatic overhead reduction</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    162. 162. HTML5 WebSocket Schemes<br /><ul><li>WebSocket</li></ul>ws://www.websocket.org/text<br /><ul><li>WebSocket Secure</li></ul>wss://www.websocket.org/encrypted-text<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    163. 163. WebSocket Architecture<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    164. 164. HTML5 WebSocket<br /><ul><li>Connection established by upgrading from the HTTP protocol to the WebSocket protocol using the same TCP connection
    165. 165. Once upgraded, WebSocket data frames can be sent back and forth between the client and the server in full-duplex mode</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    166. 166. HTML5 WebSocket Handshake<br />Client<br />GET /text HTTP/1.1Upgrade: WebSocketConnection: UpgradeHost: www.example.com<br />Origin: http://example.com<br />WebSocket-Protocol: sample… <br />Server<br />HTTP/1.1 101 WebSocket Protocol HandshakeUpgrade: WebSocketConnection: Upgrade<br />WebSocket-Origin: http://example.com<br />WebSocket-Location: ws://example.com/demo<br />WebSocket-Protocol: sample… <br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    167. 167. HTML5 WebSocket Frames<br /><ul><li>Frames can be sent full-duplex, in either direction at any the same time
    168. 168. Each frame of data:
    169. 169. Starts with a 0x00 byte
    170. 170. Ends with a 0xFF byte
    171. 171. Contains UTF-8 data in between
    172. 172. Example:
    173. 173. x00Hello, WebSocketxff</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    174. 174. Dramatic Reduction in Network Traffic<br /><ul><li>With WebSocket, each frame has only 2 bytes of packaging (a 500:1 or even 1000:1 reduction)
    175. 175. No latency involved in establishing new TCP connections for each HTTP message
    176. 176. Dramatic reduction in unnecessary network traffic and latency
    177. 177. Remember the Polling HTTP header traffic? 665 Mbps network throughput for just headers</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    178. 178. WebSocket Framing Analysis<br /><ul><li>Example network throughput overhead associated with WebSocket framing
    179. 179. Use case A: 1,000 clients receive 1 message per second: Network throughput is (2 x 1,000) = 2,000 bytes = 16,000 bits per second (~0.015 Mbps)
    180. 180. Use case B: 10,000 clients receive 1 message per second: Network throughput is (2 x 10,000) = 20,000 bytes = 160,000 bits per second (~0.153 Mbps)
    181. 181. Use case C: 100,000 clients receive 1 message per second: Network throughput is (2 x 100,000) = 200,000 bytes = 1,600,000 bits per second (~1.526 Mbps)</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    182. 182. Polling vs. WebSocket<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    183. 183. Latency Reduction<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    184. 184. Overheard…<br /> “Reducing kilobytes of data to 2 bytes…and reducing latency from 150ms to 50ms is far more than marginal. In fact, these two factors alone are enough to make WebSocket seriously interesting to Google.”<br />—Ian Hickson (Google, HTML5 spec lead)<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    185. 185. Using the WebSocket API<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    186. 186. JavaScript<br />//Checking for browser support<br />if (window.WebSocket) {<br /> document.getElementById("support").innerHTML = "HTML5 WebSocket is supported";<br /> } else {<br /> document.getElementById("support").innerHTML = "HTML5 WebSocket is not supported";<br /> }<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    187. 187. JavaScript<br />//Create new WebSocket<br />var mySocket = new WebSocket(“ws://www.websocket.org”);<br />// Associate listeners<br />mySocket.onopen = function(evt) {<br /> alert(“Connection open…”);<br />};<br />mySocket.onmessage = function(evt) {<br /> alert(“Received message: “ + evt.data);<br />};<br />mySocket.onclose = function(evt) {<br /> alert(“Connection closed…”);<br />};<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    188. 188. JavaScript<br />// Sending data<br />mySocket.send(“HTML5 WebSocket Rocks!”);<br />//Close WebSocket<br />mySocket.close();<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    189. 189. Extending WebSocket<br /><ul><li>Once you have WebSocket, you can communicate with WebSocket Servers and back-end servers and directly with message brokers
    190. 190. You can extend client-server protocols to the web:
    191. 191. XMPP, Jabber
    192. 192. Pub/Sub (Stomp/AMQP)
    193. 193. Gaming protocols
    194. 194. Any TCP-based protocol
    195. 195. Browser becomes a first-class network communication citizen</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    196. 196. Quake II Gamehttp://code.google.com/p/quake2-gwt-port<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    197. 197. WebSocket Server Support<br /><ul><li>Kaazing WebSocket Gateway
    198. 198. Apache mod_pywebsocket
    199. 199. Jetty
    200. 200. phpwebsockets
    201. 201. web-socket-ruby
    202. 202. Yaws (Erlang)
    203. 203. And more</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    204. 204. Browser Support<br /><ul><li>Chrome 4.0
    205. 205. Safari 5.0
    206. 206. Firefox 4 (Beta)</li></ul>* Emulation available through Kaazing WebSocket Gateway<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    207. 207. Q&A<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    208. 208. Resources<br /><ul><li>WebSocket specification :http://dev.w3.org/html5/websockets/
    209. 209. WebSocket protocol specification :http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
    210. 210. Web Workers specification :http://dev.w3.org/html5/workers/
    211. 211. Geolocation specification:http://dev.w3.org/geo/api/spec-source.html</li></ul>Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    212. 212. Thanks!<br />@peterlubbers<br />E-mail: peter.lubbers@kaazing.com<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />
    213. 213. Copyright © 2010 Kaazing Corporation, All rights reserved.<br />Course materials, including labs and other handouts are property of Kaazing Corporation. Except when expressly permitted by Kaazing Corporation, you may not copy, reproduce, publish, or display any part of this training material, in any form, or by any means.<br />Copyright © 2010, Kaazing Corporation,. All rights reserved.<br />

    ×