文本文稿前端html5realtime and websocket code lab_第1页
文本文稿前端html5realtime and websocket code lab_第2页
文本文稿前端html5realtime and websocket code lab_第3页
文本文稿前端html5realtime and websocket code lab_第4页
文本文稿前端html5realtime and websocket code lab_第5页
已阅读5页,还剩96页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、HTML5 Realtime and WebSocket Code LabpeterlubbersfranksalimKaazingWebSocket Demo WebSocket DemoPlink: WebSocket DemosFX Trader Application Demo Example: CollectdViewerServer Monitor System WebSocket DemosRawkets About peterlubbersSr. Director Technical CommunicationKaazing (were hiring)Author, Pro H

2、TML5 ProgrammingFounder San Francisco HTML5 User GroupHTML5 its how I rollAbout franksalimSenior Software Engineer, KaazingAuthor, Pro HTML5 ProgrammingCode-Generating Human HTML5 its how I rollAgenda Introduction to WebSocket WebSocket API WebSocket Protocol Protocol Communication Real-World WebSoc

3、ket#sfhtml5#gtugsfpeterlubbersfranksalimIntroduction to WebSocketNetworked ApplicationsOn the LAN: Reliable, real-time communicationOn the web: ?Mostly idleMostly broadcastNearly real-timeWeb + WebSockets = reliable and real-timeApproachesHTTP-basedWebSocketsHTTPHTTPHTTP is half-duplex Traffic flows

4、 in only one direction at a timeBidirectional communications are complicated to manageHTTP is statelessRedundant information is sent with each HTTP request and responseEmulating full-duplex HTTPAJAX (Asynchronous JavaScript + XML)Content can change without loading the entire pageUser-perceived low l

5、atencyComet Technique for server pushLack of a standard implementationComet adds lots of complexityPollingPolling is nearly real-timeUsed in Ajax applications to simulate real-time communicationBrowser sends HTTP requests at regular intervals and immediately receives a responseLong PollingBrowser se

6、nds a request to the server, server keeps the request open for a set periodSpeed limited by response-request-responseRequest/response headers add overhead on the wirea/k/a Asynchronous pollingStreamingMore efficient, but sometimes problematicPossible complications:Proxies and firewallsResponse build

7、s up and must be flushed periodicallyCross-domain issues to do with browser connection limitsComet Polling ExampleGET /PollingStock/PollingStock HTTP/1.1Host: localhost:8080User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:) Gecko/20091102 Firefox/3.5.5Accept: text/html,application/xhtm

8、l+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-usAccept-Encoding: gzip,deflateAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-aliveReferer: Cookie: showInheritedConstant=false; showInheritedProtectedConstant=false; showInheritedProperty=false; showInheritedPro

9、tectedProperty=false; showInheritedMethod=false; showInheritedProtectedMethod=false; showInheritedEvent=false; showInheritedStyle=false; showInheritedEffect=false;HTTP Request HeadersClientHTTP Response HeadersTotal overhead: 871 bytes (example)Often 2K+ bytese.g. cookiesHTTP/1.x 200 OKX-Powered-By:

10、 Servlet/2.5Server: Sun Java System Application Server 9.1_02Content-Type: text/html;charset=UTF-8Content-Length: 321Date: Sat, 07 Nov 2009 00:32:46 GMTServerUpload/Download Ratios Most users have Internet connections where upload to download ratios are between 1:4 and 1:20 Result: 500 byte HTTP req

11、uest header request could take as longto upload as 10 kB of HTTP response data takes to downloadHTTP Header Traffic Analysis* 871,000 bytes = 6,968,000 bits = 6.6 MbpsClientOverhead BytesOverhead Mbps1,000871,0006,6*10,0008,710,00066100,00087,100,000665Overheard Reducing kilobytes of data to 2 bytes

12、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)Enter HTML5 WebSocket!HistoryOr, what do WebSocket and model trains have in common?WebSocket HistoryOr

13、iginally added to HTML5 Spec as TCPConnection Moved to its own specificationHTML5 WebSocketCross-web communications w/ remote hostFull-duplex (bi-directional), single socketShares port with existing HTTP contentTraverses firewalls and proxiesws:/ and wss:/W3C API (Javascript)IETF ProtocolUsing the W

14、ebSocket APIvar status = document.getElementById(support);if (window.WebSocket) / or Modernizr.websocket status.innerHTML = HTML5 WebSocket is supported; else status.innerHTML = HTML5 WebSocket is not supported;JavaScriptChecking for support/Create new WebSocketvar mySocket = new WebSocket( );/ Asso

15、ciate listenersmySocket.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);JavaScriptUsing the WebSocket API/ Sending datamySocket.send(WebSoc

16、ket Rocks!);/ Close WebSocketmySocket.close();JavaScriptUsing the WebSocket APIWebSocket APIAvailable?window.WebSocket or Modernizr.websocketEventsonopen, onerror, onmessageFunctionssend, closeAttributesurl, readyState, bufferedAmount, extensions, protocol Italics: -08 and laterBrowser SupportNative

17、:Chrome 4+Safari 5+Firefox 4+Opera 10.7+Internet Explorer 10+ Emulation:Kaazing WebSocket Gatewaysocket.ioSockJSweb-socket.js (Flash)WebSocket Servers LibrariesKaazingSocket.io (node.js)Apache-websocketCrampNowjs SockJSSuperWebSocket Jetty AtmosphereAPE ProjectXsocketsOrbitedAtmosphereAutobahnCouchD

18、BNettyMisultin CowboyYAWSJuggernautPHP Websocket websockify ActiveMQHornetMQphpwebsocket Protocol:WebSocket em-websocket Jwebsocket WaterSprout ServerPywebsocketAnd moreClient LibrariesWeb-socket-js (JavaScript)AS3 WebSocket (ActionScript).NET WebSocket client (.NET)Anaida (.NET)WebSocket Sharp (.NE

19、T)Silverlight WebSocket client Java WebSocket ClientArduino C+ WebSocket clientRuby-web-socketZTWebSocket (Objective-C)Libwebsockets (C)WebSocket EmulationKaazing WebSocket Gateway Makes WebSocket work in all browsers today (including I.E. 6)Flash WebSocket implementation Requires opening port on th

20、e servers firewallSocket.io Alternate APIAdds heartbeat, timeouts and disconnectionUses Flash when availableDebugging in ChromeDebugging in ChromeLab PreviewIngredients:WebSocket-aware browser (Latest Chrome, Firefox)Python-based server (localhost or cloud)Web page w/ JavascriptSteps:Edit the page t

21、o check for browser supportAdd form handler to send messages to serverSee WebSockets in action!WebSocket BasicsLab:WebSocket Basicsthe WebSocket ProtocolWebSocket Protocol HistoryVersionDateDetails-00Jan. 9 2009Initial version-52Oct. 23 2009Subprotocol concept introduced-76May 6 2010Used in older br

22、owsers (FF4, etc.)“draft-hixie-thewebsocketprotocol-xx” IETF Network Working Group“draft-ietf-hybi-thewebsocketprotocol-xx” (IETF HyBi Working Group) VersionDateDetails-01Aug. 31 2010Added binary format-04Jan. 11 2011Introduced data masking to address proxy server security issueIntroduced including

23、protocol version number in handshake-14Sep. 8 2011Guidance on version number negotiationRFC 6455Dec. 2011Final version WebSocket HandshakeWebSocket FramesHave a few header bytesText or binary dataFrames are masked from client to serverWebSocket FramesWireshark Trace of WebSocket Basics Lab Message (

24、Client to Server)81 85 CB 6E 9F 8E 83 0B F3 E2 A4 83 0B F3 E2 A4XOR CB 6E 9F 8E CB - - - - - 48 65 6C 6C 6F H e l l oFIN bit, RSV bits, Op-CodemaskpayloadMASK bit, payloadlengthWebSocket FramesWireshark Trace of WebSocket Basics Lab Message (Server to Client)81 05 48 65 6C 6C 6F H e l l oFIN bit, RS

25、V bits, Op-CodepayloadMASK bit, payloadlengthWebSocket EfficiencyHTTPWebSocketOverhead100s of bytes2-6 bytes (typical)LatencyNew connection each timeNone: Use existing connectionLatency (polling)Wait for next intervalNo waitingLatency(long polling)None, if request sent earlier+ time to set up next r

26、equestNo waitingWebSocket Framing Analysis* 2,000 bytes = 16,000 bits (0.015 Mbps)ClientOverhead BytesOverhead Mbps1,0002,0000.015*10,00020,0000.153100,000200,0001.526Polling vs. WebSocketLatency ReductionWebSocket BenchmarkUsing CometUsing WebSocket WebSocket SummaryExtends network applications acr

27、oss the webDesktop appsBrowser-based appsMobile appsFar more efficient than HTTPPart of the HTML5 StandardOlder browsers can play tooBonus Lab:Network Traffic AnalysisProtocol CommunicationPhoto credit: zbigphotographyUsing WebSocketExtends legacy systems to the webMessage brokers, databases, etc.Ex

28、tends client-server protocols to the web:XMPP, JabberPub/Sub (Stomp/AMQP)Gaming protocolsAny TCP-based protocolRFB/VNCYour browser es a first-class network citizenTraditional ArchitectureWebSocket Architecture100% Hipster“Why?”Better responsivenessBetter scalabilityLess traffic on the wireLess work

29、for the serverEasier back-end developmentCustom commands = better match to your needsEasier migration of existing systemsJust a new UIProtocolsXMPPSTOMPMoreXMPPXMPP (Extensible Messaging and Presence Protocol)Open XML technology for presence and real-time communicationDeveloped by the Jabber communi

30、ty in 1999Formalized by the IETF in 2002-2004UsesReal-time chatClient-ServerExamples: Google Talk, iChat, FacebookXMPP XMLXMLClient Server Server Clientplus encryption, authentication, and resource bindingXMPP Conversation Hi Sean! Hi Rocky!XMLClient Server Server ClientXMPP Command SetConnect / dis

31、connectRegisterCheck rosterSend messagesSet statusCommunicate presence+ extensionsXMPP over WebSocketProposed protocol:Add xmpp to Sec-WebSocket-Protocol headerCommands: regular XMPP XMLStanzas: 1 per WebSocket frameKeepalive: WebSocket PING commandShutdown:Close XMPP stream normallyClose WebSocket

32、connectiondraft-moffitt-xmpp-over-websocket-00Google Talk Google TalkEncrypted (XMPP over TLS)Integrates w/ any service provider using XMPPHosted at on port 5222Authentication through SASL PLAINexample: Message Brokers and STOMPSTOMPStreaming Text Oriented Messaging Protocol Simple, easily-implement

33、ed protocol for use with message brokersProvides an interoperable wire formatSTOMP clients can communicate w/ almost every available message broker Apache ActiveMQOpen source message broker and JMS providerProvides a publish-subscribe model based on JMS (Java Message Service) specificationIncludes b

34、uilt-in support for STOMPSTOMP and WebSocketDirect link between the browser & JMS brokerRadically simplified application designSTOMP + WebSocket Providersstomp-websocketStompleApache ActiveMQTorqueBox (Ruby)Kaazing Web Gateway JMS editionSTOMP ProtocolMessage StructureFrame-basedRequest-responseHear

35、tbeat optionalClient CommandsServer ResponsesABORTERRORACKMESSAGEBEGINRECEIPTCOMMITCONNECTDISCONNECTSENDSUBSCRIBEUNSUBSCRIBECOMMANDheader1:value1header2:value2BodySpecification GithubLab PreviewProtocol LibrariesLab PreviewIngredients:Safari 5.0+ BrowserOthers not guaranteedApache web server (httpd)

36、Pre-installed on OS X, Windows installer providedApache ActiveMQ (localhost or cloud)IMPORTANT: Add stomp and websocket transport connectorsStock data sourceStarter filesstomp-websocket libraryHTML & CSS startersProtocol LibrariesLab:Protocol LibrariesWebSockets in the Real WorldSecuritySecurityComp

37、onents of secure communication :Transport LayerAuthenticationAuthorizationOrigin-Based Security and CORSTransport Layer Security (TLS)Also known as SSL (Secure Socket Layer) supportHTTP over TLS is called HTTPSDefault port is 443HTTPS is not a separate protocolAn HTTPS connection is established afte

38、r a successful TLS handshake (using public and private key certificates)ws:/ and wss:/ schemesAuthenticationMechanism by which systems identify users and check whether users really are who they represent themselves to beAuthentication processStep 1) Server issues a challenge using the HTTP 401 Autho

39、rization Required codeStep 2) Client responds by providing the requested authentication information if it canAuthorizationMechanism by which a system determines users level of accessFor example, a web page can have viewer, moderator, and administrator privilegesAccess rights are typically stored in

40、the policy store that is associated with the applicationWeb Origin ConceptWeb Origin Concept RFC 6454: An Origin is a subset of an address used for modeling trust relationships on the webOrigins consist of a scheme, a host, and a port:Scheme: http:, https:, ws:, wss:Host: , , 0Port: 80, 443Same-Orig

41、in Policy“Generally speaking, documents retrieved from distinct origins are isolated from each other” W3C Browsers prevent a script or document loaded from one origin from communicating with a document loaded from another origin Original security model for HTMLIntroduced in Netscape Navigator 2.0Too

42、 limiting in this age of client-side web appsOrigin Quiz Which URLs have the same Origin? * * Where 0 resolves to CORS Cross-Origin RequestsHave an Origin header Contains the requests originProduced by the browserCannot be changed by application codeDiffers from referer sic: referer is a complete UR

43、L (can include full path)Originating pages server must approve(Access-Control-Allow-* headers)CORSIntermediariesTypes of Proxy Servers Proxy ServersWebSocket protocolis unaware of proxy servers and firewallsHTTP-based handshakeProxy typeConnection eExplicitUnencrypted1. HTTP CONNECT2. WebSocket conn

44、ection flows to destinationExplicitEncryptedTransparentUnencryptedProxy strips extra headers, connection failsTransparentEncryptedConnection tunnels past proxyCase 1 Unencrypted WebSocket Connections and Explicit Proxy ServersCase 2 Unencrypted WebSocket Connections and Transparent Proxy ServersCase 3 Encrypted WebSocket Connections and Explicit Proxy ServersCase 4 Encrypted WebSocket Connections and Transparent Proxy ServersProxy Travers

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论