v2 peter-lubbers-sf-jug-websocket

92
1 HTML5 WebSocket & Communication By Peter Lubbers, Kaazing San Francisco Java User Group Meeting May 11, 2010

Upload: brent-bucci

Post on 10-May-2015

3.801 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: V2 peter-lubbers-sf-jug-websocket

1

HTML5 WebSocket

& Communicatio

n By Peter Lubbers,

Kaazing

San Francisco Java User Group MeetingMay 11, 2010

Page 2: V2 peter-lubbers-sf-jug-websocket

2

About Peter Lubbers• Director of Documentation and Training, Kaazing

Yes, we’re hiring!• Co-Founder San Francisco HTML5 User Group

http://www.sfhtml5.org/• Ultra Distance Runner• Twitter: @peterlubbers• Co-author Pro HTML5 Programming

o Alpha Release: www.prohtml5.como Special 50% Off Coupon Code:

APRESSPROHTML5WR (expires May 31st)

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 3: V2 peter-lubbers-sf-jug-websocket

3

New HTML5 User Groups!

Copyright © 2010 - Kaazing Corporation. All rights reserved.

• San Franciscohttp://www.sfhtml5.org/First meetup: 28 May

• New Yorkhttp://www.meetup.com/NY-HTML5-User-Group/First meetup: 16 June

• Londonhttp://www.meetup.com/LondonHTML5UG/First meetup: 19 May

Page 4: V2 peter-lubbers-sf-jug-websocket

4

Agenda• HTML5 WebSocket

o Tin-can communicationo Meet HTML5 WebSocketo HTML5 WebSocket in the enterpriseo Scaling through simplicity

• HTML5 Communicationo Server-Sent Eventso XMLHttpRequest Level 2o Cross Document Messaging

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 5: V2 peter-lubbers-sf-jug-websocket

5

HTML5 WebSocket

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 6: V2 peter-lubbers-sf-jug-websocket

6

Today’s Requirements• Today’s Web applications demand reliable, real-

time communications with near-zero latency• Not just broadcast, but bi-directional

communication• Examples:

o Financial applicationso Social networking applicationso Online gameso Smart power grid

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 7: V2 peter-lubbers-sf-jug-websocket

7

The Perils of Polling

Copyright © 2010 - Kaazing Corporation. All rights reserved.

No-Fly list not updated…

Page 8: V2 peter-lubbers-sf-jug-websocket

8

HTTP Is Not Full Duplex

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 9: V2 peter-lubbers-sf-jug-websocket

9

About HTTP• HTTP was originally designed for document

transfer• Until now, it has been cumbersome to achieve

real-time, bi-directional web communication due to the limitations of HTTP

• HTTP is half-duplex (traffic flows in only one direction at a time)

• Header information is sent with each HTTP request and response, which can be an unnecessary overhead

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 10: V2 peter-lubbers-sf-jug-websocket

10

About Ajax and Comet• Great toilet cleaners…• Ajax (Asynchronous JavaScript and XML)

can be used to build interactive Web appso Content can change without refreshing the

entire pageo User-perceived low latency

• “Real-time” often achieved through polling and long-polling (Comet or Reverse Ajax)o Comet lack of a standard implementationo Comet adds lots of complexity

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 11: V2 peter-lubbers-sf-jug-websocket

11

Half-Duplex Architecture

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 12: V2 peter-lubbers-sf-jug-websocket

12

Polling Architecture

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 13: V2 peter-lubbers-sf-jug-websocket

13

Polling• Polling is “nearly real-time”• Used in Ajax applications to simulate real-

time communication• Browser sends HTTP requests at regular

intervals and immediately receives a response

• In low-message-rate situations, many connections are opened and closed needlessly

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 14: V2 peter-lubbers-sf-jug-websocket

14

Long Polling Architecture

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 15: V2 peter-lubbers-sf-jug-websocket

15

Long Polling• Also known as asynchronous-polling• Browser sends a request to the server

and the server keeps the request open for a set period

• HTTP headers, present in both long-polling and polling often account for most of the network traffic

• In high-message rate situations, long-polling results in a continuous loop of immediate polls

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 16: V2 peter-lubbers-sf-jug-websocket

16

Streaming Architecture

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 17: V2 peter-lubbers-sf-jug-websocket

17

Streaming• More efficient, but sometimes problematic• Possible complications:

o Proxies and firewallso Response builds up and must be flushed

periodicallyo Cross-domain issues to do with browser

connection limits

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 18: V2 peter-lubbers-sf-jug-websocket

18

Comet Demo

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 19: V2 peter-lubbers-sf-jug-websocket

19

HTTP Request HeadersPOST /gwt/EventService HTTP/1.1Host: gpokr.comConnection: keep-aliveUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US)

AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.1.249.1064 Safari/532.5Referer: http://gpokr.com/gwt/7F5E66657B938E2FDE9CD39095A0E9E6.cache.htmlContent-Length: 134Origin: http://gpokr.comContent-Type: text/plain; charset=utf-8Accept: */*Accept-Encoding: gzip,deflate,sdchAccept-Language: en-US,en;q=0.8Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3Cookie: __utmz=247824721.1273102477.1.1.utmcsr=(direct)|utmccn=(direct)|

utmcmd=(none); JSESSIONID=E7AAE0E60B01FB88D1E3799FAD5C62B3; __utma=247824721.1247485893.1273102477.1273104838.1273107686.3; __utmc=247824721; __utmb=247824721.4.10.127

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 20: V2 peter-lubbers-sf-jug-websocket

20

HTTP Response Headers200 OKServer: Apache-Coyote/1.1Expires: Thu, 06 May 2010 01:06:51 GMTContent-Type: text/plain;charset=UTF-8Content-Length: 303Date: Thu, 06 May 2010 01:06:50 GMT

• Total (unnecessary) HTTP request and response header information overhead: 871 bytes (example)

• Overhead can be as much as 2000 bytes

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 21: V2 peter-lubbers-sf-jug-websocket

21

HTTP Header Traffic Analysis• Example network throughput for HTTP request

and response headers associated with polling• Use case A: 1,000 clients polling every second:

• Network throughput is (871 x 1,000) = 871,000 bytes = 6,968,000 bits per second (~6.6 Mbps)

• Use case B: 10,000 clients polling every second:• Network throughput is (871 x 10,000) = 8,710,000 bytes =

69,680,000 bits per second (~66 Mbps)

• Use case C: 100,000 clients polling every second:• Network throughput is (871 x 100,000) = 87,100,000 bytes =

696,800,000 bits per second (~665 Mbps)

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 22: V2 peter-lubbers-sf-jug-websocket

22

Comet: Headache 2.0

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 23: V2 peter-lubbers-sf-jug-websocket

23

Complexity does not scale

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 24: V2 peter-lubbers-sf-jug-websocket

24

Vote NO on Tin Cans and String for

Communication!

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 25: V2 peter-lubbers-sf-jug-websocket

25

Enter HTML5 WebSocket!

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 26: V2 peter-lubbers-sf-jug-websocket

26

HTML5 WebSocket• W3C API and IETF Protocol• Full-duplex text-based socket• Enables web pages to communicate with a

remote host• Traverses firewalls, proxies, and routers

seamlessly• Leverages Cross-Origin Resource Sharing

(CORS)• Share port with existing HTTP content

(80/443)

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 27: V2 peter-lubbers-sf-jug-websocket

27

Pop QuizWhat does WebSocket have in common with

model trains?

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 28: V2 peter-lubbers-sf-jug-websocket

28

Possible WebSocket Architecture

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 29: V2 peter-lubbers-sf-jug-websocket

29

HTML5 WebSocket Schemes• WebSocket

o ws://www.websocket.org/text

• WebSocket Secureo wss://www.websocket.org/encrypted-text

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 30: V2 peter-lubbers-sf-jug-websocket

30

HTML5 WebSocket• Connection established by upgrading from

the HTTP protocol to the WebSocket protocol using the same TCP connection

• Once upgraded, WebSocket data frames can be sent back and forth between the client and the server in full-duplex mode

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 31: V2 peter-lubbers-sf-jug-websocket

31

HTML5 WebSocket Handshake

GET /text HTTP/1.1Upgrade: WebSocketConnection: UpgradeHost: www.example.comOrigin: http://example.comWebSocket-Protocol: sample…\r\n

Client

HTTP/1.1 101 WebSocket Protocol HandshakeUpgrade: WebSocketConnection: UpgradeWebSocket-Origin: http://example.comWebSocket-Location: ws://example.com/demoWebSocket-Protocol: sample…\r\n

Server

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 32: V2 peter-lubbers-sf-jug-websocket

32

HTML5 WebSocket Frames• Frames can be sent full-duplex, in either

direction at any the same time• Each frame of data:

o Starts with a 0x00 byte and End with a 0xFF byteo Contains UTF-8 data in between

• Example:o \x00Hello, WebSocket\0xff

• There is no defined maximum sizeo If the user agent has content that is too large to be

handled, it must fail the Web Socket connectiono JavaScript does not allow >4GB of data, so that is

a practical maximumCopyright © 2010 - Kaazing Corporation. All rights reserved.

Page 33: V2 peter-lubbers-sf-jug-websocket

33

Using the WebSocket API

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 34: V2 peter-lubbers-sf-jug-websocket

34

//Checking for browser supportif (window.WebSocket) { document.getElementById("support").innerHTML = "HTML5 WebSocket is supported"; } else { document.getElementById("support").innerHTML = "HTML5 WebSocket is not supported"; }

JavaScript

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Checking For Browser Support

Page 35: V2 peter-lubbers-sf-jug-websocket

35

//Create new WebSocketvar mySocket = new WebSocket(“ws://www.websocket.org”);

// Associate listenersmySocket.onopen = function(evt) {

alert(“Connection open…”);};

mySocket.onmessage = function(evt) {alert(“Received message: “ + evt.data);

};

mySocket.onclose = function(evt) {alert(“Connection closed…”);

};

JavaScript

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Using the WebSocket API

Page 36: V2 peter-lubbers-sf-jug-websocket

36

// Sending datamySocket.send(“HTML5 WebSocket Rocks!”);

//Close WebSocketmySocket.close();

JavaScript

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Using the WebSocket API

Page 37: V2 peter-lubbers-sf-jug-websocket

37

Browser Support for WebSocket

• Chrome 4.0+• WebKit Nightly builds• Support planned for Firefox:

“We really really want to support WebSockets in the next version of Firefox.” –Christopher Blizzard, Mozilla

Dev channel

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 38: V2 peter-lubbers-sf-jug-websocket

38

Example: Native WebSocket in Chrome

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 39: V2 peter-lubbers-sf-jug-websocket

39

WebSocket Emulation• Kaazing WebSocket Gateway

• http://www.kaazing.com/download• Makes WebSocket work in all browsers today

(including I.E. 6)

• Flash WebSocket implementation• http://github.com/gimite/web-socket-js• Requires opening port on the server’s firewall 

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 40: V2 peter-lubbers-sf-jug-websocket

40

Beyond WebSocket• Once you have WebSocket, you can

communicate with WebSocket Servers and back-end servers and directly with message brokers

• You can extend client-server protocols to the web:• XMPP, Jabber• Pub/Sub (Stomp/AMQP)• Gaming protocols• Any TCP-based protocol

• Browser becomes a first-class network communication citizen

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 41: V2 peter-lubbers-sf-jug-websocket

41

Financial Applications

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 42: V2 peter-lubbers-sf-jug-websocket

42

Example: WebSocket-Based Quake II Game Port

http://code.google.com/p/quake2-gwt-port Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 43: V2 peter-lubbers-sf-jug-websocket

43

Twitter Feed

http://kaazing.me Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 44: V2 peter-lubbers-sf-jug-websocket

44

WebSocket in the Enterprise

 

Page 45: V2 peter-lubbers-sf-jug-websocket

45

WebSocket and Web Intermediaries• Web Socket protocol itself is unaware of proxy

servers and firewalls• WebSocket features an HTTP-compatible

handshake so that HTTP servers can share their default HTTP and HTTPS ports (80 and 443) with a WebSocket server

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 46: V2 peter-lubbers-sf-jug-websocket

46

Securing WebSocket Traffic• WebSocket defines the ws:// and wss://

schemes• WSS is WS over TLS (Transport Layer Security),

formerly known as SSL (Secure Socket Layer) support (Similar to HTTPS)

• An HTTPS connection is established after a successful TLS handshake (using public and private key certificates)

• HTTPS is not a separate protocol, but it is HTTP running on top of a TLS connection (default ports is 443)

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 47: V2 peter-lubbers-sf-jug-websocket

47

Proxy Servers• A proxy server is a server that acts as an

intermediary between a client and another server (for example, a web server on the Internet)

• Commonly used for content caching, Internet connectivity, security, and enterprise content filtering

• May also buffer unencrypted HTTP responses, thereby introducing unpredictable latency during HTTP response streaming

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 48: V2 peter-lubbers-sf-jug-websocket

48

Types of Proxy Servers

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 49: V2 peter-lubbers-sf-jug-websocket

49

WebSocket Proxy Traversal

Copyright © 2010 - Kaazing Corporation. All rights reserved.

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

Page 50: V2 peter-lubbers-sf-jug-websocket

50

Load Balancing Routers• TCP (layer-4) load-balancing routers should

work well with HTML5 Web Sockets, because they have the same connection profile: connect once up front and stay connected, rather than the HTTP document transfer request-response profile

• HTTP (Layer 7) load-balancing routers expect HTTP traffic and can easily get confused by WebSocket upgrade traffic. For that reason, Layer 7 load balancing routers may need to be configured to be explicitly aware of WebSocket traffic

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 51: V2 peter-lubbers-sf-jug-websocket

51

Firewalls• Since firewalls normally just enforce the rules

for inbound traffic rejection and outbound traffic routing (for example, through the proxy server), there are usually no specific WebSocket traffic-related firewall concerns

• For regular socket connections (for example, for a desktop client) you must open a port on the firewall

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 52: V2 peter-lubbers-sf-jug-websocket

52

WebSocket Traffic Analysis

 

Page 53: V2 peter-lubbers-sf-jug-websocket

53

WebSocket Demo

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 54: V2 peter-lubbers-sf-jug-websocket

54

Dramatic Reduction in Network Traffic

• With WebSocket, each frame has only 2 bytes of packaging (a 500:1 or even 1000:1 reduction)

• No latency involved in establishing new TCP connections for each HTTP message

• Dramatic reduction in unnecessary network traffic and latency

• Remember the Polling HTTP header traffic? 665 Mbps network throughput for just headers

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 55: V2 peter-lubbers-sf-jug-websocket

55

WebSocket Framing Analysis• Example network throughput overhead

associated with WebSocket framing• 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)

• 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)

• 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)

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 56: V2 peter-lubbers-sf-jug-websocket

56

Polling vs. WebSocket

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 57: V2 peter-lubbers-sf-jug-websocket

57

Latency Reduction

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 58: V2 peter-lubbers-sf-jug-websocket

58

Overheard… “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.”—Ian Hickson (Google, HTML5 spec lead)

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 59: V2 peter-lubbers-sf-jug-websocket

59

HTML5 Communication

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 60: V2 peter-lubbers-sf-jug-websocket

60

HTML5 CommunicationHTML5 defines a few more handy communication

features:• Cross Document Messaging• XMLHttpRequest Level 2• Server-Sent Events

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 61: V2 peter-lubbers-sf-jug-websocket

61

Cross Document Messaging• Enables secure cross-origin communication

across iframes, tabs, and windows (using origin security)

• Defines the PostMessage API as a standard way to send messages

• Provides asynchronous message passing between JavaScript contexts

• HTML5 clarifies and refines domain security by introducing the concept of an origin

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 62: V2 peter-lubbers-sf-jug-websocket

62

Same-Origin Policy• The browsers’ same-origin policies prevent a

script (or document) loaded from one origin from communicating with a document loaded from another origin

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 63: V2 peter-lubbers-sf-jug-websocket

63

Origin Concept• An origin is a subset of an address used for

modeling trust relationships on the Web• Origins are made up of a scheme, a host,

and a port—different origin:o https://www.example.com o http://www.example.com

• The path is not considered in the origin value—same origin:o http://www.example.com/index.htmlo http://www.example.com/page2.html

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 64: V2 peter-lubbers-sf-jug-websocket

64

Cross Document Messaging• When you send a message, the sender specifies

the receiver’s origin• When you receive a message, the sender’s origin

is included as part of the message (The message’s origin is provided by the browser and cannot be spoofed)

• This allows you to decide which messages to process and which to ignore

• You can keep a white list and process only messages from documents with trusted origins

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 65: V2 peter-lubbers-sf-jug-websocket

65

PostMessage Architecture

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 66: V2 peter-lubbers-sf-jug-websocket

66

PostMessage API• The PostMessage API can be used for

communicating between documents with the same origin

• PostMessage provides asynchronous message passing between JavaScript contexts.

• Useful when communication might otherwise be disallowed by the same-domain policy

• Also provides a consistent, easy-to-use API• Also used in other HTML5 APIs for communication

between JavaScript contexts, for example in HTML5 Web Workers

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 67: V2 peter-lubbers-sf-jug-websocket

67

Using the PostMessage API

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 68: V2 peter-lubbers-sf-jug-websocket

68

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

Copyright © 2010 - Kaazing Corporation. All rights reserved.

JavaScript

Using the PostMessage API

Page 69: V2 peter-lubbers-sf-jug-websocket

69

//Listening for messages:window.addEventListener(“message”, messageHandler, true);

function messageHandler(e) { switch(e.origin) { case “friend.example.com”: // process message processMessage(e.data); break; default: // message origin not recognized // ignoring message }}

Copyright © 2010 - Kaazing Corporation. All rights reserved.

JavaScript

Using the PostMessage API

Page 70: V2 peter-lubbers-sf-jug-websocket

70

Browser Support for Cross Document Messaging

Copyright © 2010 - Kaazing Corporation. All rights reserved.

• Chrome 2.0+• Firefox 3.5+• IE 8.0+• Opera 9.6+• Safari 4.0+

Page 71: V2 peter-lubbers-sf-jug-websocket

71

XMLHttpRequest Level 2• XMLHttpRequest Level 2• XMLHttpRequest is the API that made Ajax

possible• XMLHttpRequest Level 2 significantly

enhances XMLHttpRequest o Progress eventso Cross-origin XMLHttpRequest

• XMLHttpRequest Level 2 allows for cross-origin XMLHttpRequests using Cross Origin Resource Sharing (CORS)http://www.w3.org/TR/access-control/

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 72: V2 peter-lubbers-sf-jug-websocket

72

Cross-origin HTTP requests• Cross-origin HTTP requests have an Origin

header that provides the server with the request’s origin

• This header is protected by the browser and cannot be changed from application code

• In essence, a network equivalent of the origin property found on message events used in Cross Document Messaging.

• The origin header differs from the older referer [sic] header in that the referer is a complete URL including the path

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 73: V2 peter-lubbers-sf-jug-websocket

73

POST /main HTTP/1.1Host: www.example.netUser-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.3Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip,deflateAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-aliveReferer: http://www.example.com/pathOrigin: http://www.example.comPragma: no-cache

Copyright © 2010 - Kaazing Corporation. All rights reserved.

JavaScript

Origin and Referer (Request)

Page 74: V2 peter-lubbers-sf-jug-websocket

74

HTTP/1.1 201 CreatedTransfer-Encoding: chunkedServer: Kaazing GatewayDate: Mon, 02 Nov 2009 06:55:08 GMTContent-Type: text/plainAccess-Control-Allow-Origin: http://www.example.comAccess-Control-Allow-Credentials: true

Copyright © 2010 - Kaazing Corporation. All rights reserved.

JavaScript

Origin and Referer (Response)

Page 75: V2 peter-lubbers-sf-jug-websocket

75

Progress Events• One of the most important API improvements in

XMLHttpRequest have been the changes related to progressive responses

• Before XHR Level 2:o There was only a single readystatechange evento Inconsistently implemented across browsers (for

example, readyState 3  (progress) never fires in Internet Explorer)

o Lacked a way to communicate upload progress. Implementing (for example, building an upload progress bar was not a trivial task)

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 76: V2 peter-lubbers-sf-jug-websocket

76

Progress Events• XMLHttpRequest Level 2 supports named

progress events:o loadstarto progresso aborto erroro loado loadend

• readyState property and readystatechange events retained for backward compatibility

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 77: V2 peter-lubbers-sf-jug-websocket

77

Using the XMLHttpRequest API

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 78: V2 peter-lubbers-sf-jug-websocket

78

Progress Events• Progress events have fields for:

o The total amount of data to transfero The amount that has already transferredo Whether the total is known (Boolean value)

crossOriginRequest.upload.onprogress = function(e) { var total = e.total; var loaded = e.loaded;

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

JavaScript

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 79: V2 peter-lubbers-sf-jug-websocket

79

Cross-Origin XMLHttpRequest

• XMLHttpRequest Level 2 allows for cross-origin XMLHttpRequests using Cross Origin Resource Sharing (CORS)http://www.w3.org/TR/access-control/

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

JavaScript

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 80: V2 peter-lubbers-sf-jug-websocket

80

Browser Support for XMLHttpRequest Level 2

Copyright © 2010 - Kaazing Corporation. All rights reserved.

• Chrome 2.0+ • Firefox 3.5+• Safari 4.0+

• Note: some server side participation may be required (CORS)

Page 81: V2 peter-lubbers-sf-jug-websocket

81

HTML5Server-Sent Events

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 82: V2 peter-lubbers-sf-jug-websocket

82

Server-Sent Events• Server-Sent Events (SSE) standardizes and

formalizes how a continuous stream of data can be sent from a server to a browser

• Effectively standardizes Comet and Reverse Ajax• EventSource API for broadcasting data from

server to client• SSE is compatible with almost any setup that uses

HTTP today (WebSocket requires that intermediaries support full-duplex connections)

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 83: V2 peter-lubbers-sf-jug-websocket

83

Server-Sent Events• Server-Sent features

o Reconnectiono Event IDso Ability to send arbitrary events

• Server-Sent Events can be used for automated data push mechanisms (for example, updating Web Storage)

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 84: V2 peter-lubbers-sf-jug-websocket

84

SSE Architecture

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 85: V2 peter-lubbers-sf-jug-websocket

85

Using the EventSource API

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 86: V2 peter-lubbers-sf-jug-websocket

86

//Connects to a server URL to receive an event stream:var stream = new EventSource("http://news.kaazing.com");

Set event handlers:stream.onopen = function() { alert(“open”); } stream.onmessage = function(event) { alert(“message: “ + event.data); }stream.onerror = function() { alert(“error”); }

Copyright © 2010 - Kaazing Corporation. All rights reserved.

JavaScript

Using the EventSource API

Page 87: V2 peter-lubbers-sf-jug-websocket

87

Example: News Broadcast

Copyright © 2010 - Kaazing Corporation. All rights reserved.

http://kaazing.me/

Page 88: V2 peter-lubbers-sf-jug-websocket

88

Browser Support for Server-Sent Events

Copyright © 2010 - Kaazing Corporation. All rights reserved.

• Opera 9.0+ partial support• Development in Firefox Trunk

Dev channel

Page 89: V2 peter-lubbers-sf-jug-websocket

89

Q&A

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 90: V2 peter-lubbers-sf-jug-websocket

90

SF JUG HTML5 Meeting Special!

Copyright © 2010 - Kaazing Corporation. All rights reserved.

10% Off Any HTML5 Training

With Coupon Code HTML5ROCKShttp://tech.kaazing.com/training/index.html

HTML5ROCKS

Page 91: V2 peter-lubbers-sf-jug-websocket

91

Copyright © 2010 Kaazing Corporation, All rights reserved.All 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.

Copyright © 2010 - Kaazing Corporation. All rights reserved.

Page 92: V2 peter-lubbers-sf-jug-websocket

92