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.

Introduction to WebSockets

3,007 views

Published on

Overview of WebSockets (protocol and Java EE7 support)
by Erin Schnabel (Liberty Profile Development Lead, IBM | @ebullientworks)

Published in: Technology
  • Be the first to comment

Introduction to WebSockets

  1. 1. Introduction to Websoekets Session 1641 Erin Schnabel Liberty Runtime Development Lead, IBM @ebu/ /ientworks | nterConnect 2015 The Premier Cloud 8. Mobile Conference February 22 - 26 MGM Grand 8. Mandalay Bay I Las Vegas. Nevada 20 l 5 «IBM Curpu: allot‘
  2. 2. .-"'- 5 ': (“, l l l i C: /NF" ’ "‘ . I ‘I , ' ‘L, ’ '. . . . » ‘~. .»‘ K} J . ' ‘J . . _/ WebSocket network protocol - Data format WebSocket API (Javascript & Java EE) - Endpoint configuration - Session open/ close - Message read/ write - Error handling - Annotations Network architecture - Proxies / load balancers / routers. .. Inter Connect iitbminterconnect
  3. 3. Mbmlntetconnect <'tri pDO~. /Hl/ l€mOl'yl_3lT€>° Before /1/ebSockets. .. . fli"t'iiIel: ‘li‘t. 201 5 The Premier Cloud & Mobile Conference
  4. 4. Options for two-way communication - Polling - Long polling - Streaming / forever response - Multiple connections Interconnect 2015 Jtibmimerconnect
  5. 5. GA 2 i time I: T lll‘ T" l lll‘ Client polls the server every n Server always immediately responds (with or without data) Might work for periodic data where the period is known/ constant BUT. .. Inter Connect iitbminterconnect
  6. 6. (1): Polling I’ ll lllllfllll I ll. .11 la! AA A T time - Client polls the server every n - Server always immediately responds (with or without data) - Might work for periodic data where the period is known/ constant - Obvious waste (CPU and bandwidth) when there is no data IITEGTCOHTIGCE 2 O l 5 '3 fibunlnblconnoct
  7. 7. (2): Long Polling - Client sends initial request - Server waits until it has data to respond - Client receives response, and immediately creates new request - Obvious improvement over plain polling BUT. .. lnterConnect2015 7 Oibunlnhxconnoct
  8. 8. “W ~ I! ;— -, <4), !. ..o. ::; ;, c. .~: .;: r. J l time . LSOd d. l_LH ‘ ll: ill’ I "if , Ill . Client sends initial request Server waits until it has data to respond Client receives response, and immediately creates new request Obvious improvement over plain polling Each request/ response creates and closes a connection Client has to wait to send new data until the server responds Inter Connect ittbminterconnect
  9. 9. F , V , "“. '», 1/ A"~ ‘ , ‘ / ‘- r"f . }. ,v"‘ '‘ (E I": L. ) lJl/ ' _/ l ! _», '!J. )I: _/ '~_/ time ll lll' ll. , | ll'_ Client sends initial request Server waits until it has data to respond Server responds by streaming data - Server has an open connection to push updates Connection is maintained BUT. .. Inter Connect ittbminterconnect
  10. 10. (3): Streaming / forever response - Client sends initial request - Server waits until it has data to respond - Server responds by streaming data - Server has an open connection to push updates - Connection is maintained - It is ha/ f-dup/ ex: only server to client - User agents and proxies might not like partial responses Inter Connect 2 U l 5 Ilibminterconnect
  11. 11. , V . _ . -. ,« (~ — —~, . , ---. ' ’— _. » lo. ’ (x Iw» . . l_.1,. . . , . ll 1 l lL. 'I; .‘J «Q ‘kxc. /I ll l. ‘_»x/ ~. 1/. IV‘ l--‘ [1 {o4 N‘ ‘ lJ ‘: ~--' ~]1 - "Tat /7 :2: :1: : : §: r- I 1. I: § 1 =1 3 '-al ~a -.2 -a H7 -3 . ~a' 8 3 8 fl ‘Q 9. *2 all A is -‘4_‘}’_4 ' Long polling over two separate HTTP connections - Approximation of bi-directional connection - Two connections are used (HTTP recommended max) — long polling — second connection allows client to send data to the server BUT. .. Inter Connect ittbminterconnect
  12. 12. I :3 I L . N time 1504 -19.“. T. d_ dLJ. H T . LSOd <| .l. LH Z ‘Jl. SOd d. LLH Z ’ tsp; a1In‘r‘ ‘ I . . . . ' _1‘soa’4uH I" AIS Long polling over two separate HTTP connections - Approximation of bi-directional connection - Two connections are used (HTTP recommended max) — long polling — second connection allows client to send data to the server Non-trivial connection coordination and management Two connections for every client Inter Connect rttbminterconnect
  13. 13. Hidden cost of HTTP. .. - TCP handshake when establishing new connection - Even worse for SSL. .. - HTTP headers on every message - Always present, can vary in size and quantity GET / Pollingstock/ /Polltngstock HTTP/1. 1 Host: locauaont: HOBO User-Agent: Hozxlla/5.0 (Windows; U; wmdowa NT 5.1; an-US; rv:1.9.1.5) Gecko/20091102 Piretox/3.5.5 Accept: text: /hcml, application/ xht-. m1+x: m1 , application/ xm.1;q-O . 9 , -I' ; q-0 . B Accept-Language 2 an-us Accept-Encoding: qz. ‘|p, def1ate For small messages. you Accapt—Charnetx I50-8B59—l, utt-B; q-0.7,°; q'-0.7 Keep-mm =00 around more HTTP Connection: keep-alive headers than data! htlpllwww websockel orglquanlum hlml Rnterer: http x I / mow. example. con/ Pol]J. nqsr. oc)d Interconnect 2015 “ 5 flbmtnbroonnoct
  14. 14. lflbmmtetconnect </ tripDownlvlemoryLene> il"r'lE: er*i‘r. 201 5 The Premier Cloud & Mobile Conference
  15. 15. There is a better way: WebSockets - Bi-directional - Client and server can send messages at any time - Full duplex - Client and server can send updates at the same time - No requirement for request/ response pair or message ordering - Single long running connection with established context - No connection management/ coordination - Connection upgraded from HTTP - No new connection protocol to build infrastructure for - Efficient use of bandwidth and CPU - Messages can focus on application data InterConnect 2 Ol 5 llibmlntexconnect
  16. 16. WebSockets have been standardized - IETF RFC-6455: WebSocket Protocol Specification, 2011 - JSR 356: WebSocketAP| Specification, 2013 - Part of Java EE 7 lnterConnect2015 Web Sockets I —CR Global 84.54% + 1.42% = 85.96% . _ . _ _ unprefixed: 84.S4%+ 1.27%: 85.81% Bidirectional communication technology for web apps I’ Criurviu Ell: -lllgael ‘ is Fm-ivx arm 54» Ow» sL? .?. .- °t: .‘I. “- 8§§': - ‘”a‘. ’:', ‘.. °:; '* , ,.: ;:', ,.. “, £Si? .L'§' ‘Wm , ,.; =,'w llibmimexconnect
  17. 17. But. .. - What about plain HTTP requests? - HTTP is still great for loading static resources! - What about REST? - REST is still great for client-initiated CRUD operations - What about MQTT? - Pub/ Sub model, different QOS, different protocol - Runs atop WebSockets! (Liberty/ Rtcomm, Paho. js, .. .) Inter Connect 2 C l llibminterconnect
  18. 18. lflbmmtetconnect <bé‘: _CkQI"OL! l'lCl>‘ -low WebSocl<ets ~/ oi'l<. _ ii‘itf: ei*i‘r 20“i 5 The Premier Cloud & Mobile Conference
  19. 19. time _'l Handshake: ' Client initiates connection ° Server responds (accepts the upgrade) Inter Connect rttbminterconnect
  20. 20. jl " g_open_, I T gmso»-i'_ msg V 3 _ Fl c T Handshake: ' Client initiates connection ° Server responds (accepts the upgrade) Once the WebSocket is established - both sides notified that socket is open error fgmsg: ‘ i _c| ose/ A v either side can send messages at any time ° either side can close the socket Interconnect it tbminterconnect time
  21. 21. WebSocket Protocol: it starts with a handshake. .. GET / myapp HTTP/1.1 Host: server. example. com Upgrade: websocket , c, ,,, ,,, cti°, ,, upgrade } Request upgrade to WebSocket connection Sec-Websocket-Key: Gh1IHNhbXBsZSBub25jZQ= = Sec-Websocket-Version: 13 8ec—WebSocl¢ot-Protocol: custom WebSocket handshake Sec~flhbsocket—Extensions: compress headers Origin: http: //example. com request HTTP/1.1 101 Switching Protocols Host: server. example. com Upgrade: websocket Connection: Upgrade Sec-Hebsocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+x0o= Sec-Nbbsocket-Protocol: custom Sec-Nbbsocket-Extensions: compress response | nterconnect2015 sr inbmlrxhtconnoct
  22. 22. . and then transitions to frames 0 1 3 0 1 2 3 4 5 6 7 8 9 O 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 O 1 FIRIRIRI opcode Ilslslsl (4) N| V|V| V| |1|2|3| yload length co tinned, if paylad len -- 127 if N‘ = ° 1 Masking-key (c-ntinued) Payload Data I _ _ __ _— _ __ __ . . _ _ -l Payload Data continued . .. Payload len (7) Extended pa load length (if payload en--126/127) - Data or text is transmitted in frames - Minimally framed: small header, then payload Interconnect 2015 inbmlnhtconnoct
  23. 23. Messages can be fragmented across frames 0 1 2 3 1234567890123456789012345678901 Extended pa load length (1 /64) (if payload en--126/127) IRIRI opcode M] Payload len ‘ Al (7) W I yload length co tinned, if paylad len -- 127 if W t° 1 Payload Data I - Message can be in one or more frames - Continue until FIN - Aframe contains data for only one message - Extensions can be used to multiplex connections Interconnect2015 . — iimmmmonneci
  24. 24. /‘x l ' i ~'* * (W _ ~ « — ——. ,«— _ t v, , I ‘, —_ , , /-t , . ‘x. /U! ) K. ,z'()‘c'/ Vt‘) l&. »_»ll. _lil“ll]‘; ./' l! l_1J'k</ ‘Cg. / Q Control frames - Ping — OxA - Pong — 0x9 ° Close — 0x8 Data frames - Text — 0x1 — UTF-8 - Binary — 0x2 — Arbitrary content: up to the application layer to determine Additional op codes are defined by negotiated extensions - Use reserved flags in the header Inter Connect rttbminterconnect
  25. 25. </ ?3ecl<grounc5> ii‘itf: ei*i‘r 20“i 5 The Premier Cloud & Mobile Conference lflbmmtetconnect
  26. 26. 0 How do we use WebSockets in an application? Interconnect O l 5 llibminterconnect
  27. 27. Websockets API (JavaScript) - Developed as part of HTML5: - http: //dev. w3.org/ htm|5/websockets/ interface websocket : EventTarget { readonty attribute DOMString ggl; / / ready state const unsigned short CQNNEQIINQ = 0; const unsigned short QEEN = 1; const unsigned short QLQSINQ = 2; const unsigned short §LQ5EQ = 3; readonly attribute unsigned short Leadystajg; readonty attribute unsigned long bujjeLegAmguflt; / / networking attribute EventHand1er gngpen; attribute EventHandter gngrrg ; attribute EventHand1er gnglgse; readonly attribute DOMString extensions; readonty attribute DOMString prgtogol; void ctose([C1amp] optional unsigned short code, optional DOMString reason); / / messaging attribute EventHand1er gnmgssagg; attribute liinarxlxns: i void send(DOMString data): void §§nQ(B1ob data); void £§nd(ArrayBuffer data); void §§fld(ArrayBufferView data); }: Interconnect 2015 lftbminterconnect 27
  28. 28. ("—'. .~' ' " . a/ soc; |: ,J’L CIICHL mvo<: e:; :on. websocket = new WebSocket('ws: //' + window. document.1ocation. host + '/ websocket/ EchoEndpoint'); H websocket. onerror i. . websocket. onopen = i. . websocket. onc1ose = function(event) { j. . websocket. onmessage = function(event) { j. . function(event) { function(event) { Interconnect 7 fiibminterconnect
  29. 29. " F‘ H‘ _: .. «. : i I -w : r M-. V ' if x‘ / ,/ — V 3 L__ F», If‘. .v , ~., : (‘> _/7: i__, l ( I / . 1- ,3 I ‘ _/ . J V‘ ~_: . ~. V . .~_') I ‘.1 i u _ . «L. ' Programmatic or annotation-based approach Client and Server Endpoints - Havea lifecycle — onOpen — onC| ose — onError - Communicate using Messages — onMessage - send v Use sessions Encoders and Decoders deal with data formatting - Messages <--)Java Objects SPI: extensions and data frames Interconnect #4 ibmintexconnect
  30. 30. Server Endpoint: Annotated - Simple POJO with rise rvc-: rEndpoir1t annotation - value is the URI relative to your app’s context root, e. g. ws: //localhost/ myapp/ SimpleAnnotated - Annotations for notifications: lifecycle and messages @ServerEndpoint(value = "/ SimpleAnnotated") public class SimpleEndpoint { @0n0pen public void on0pen(Session session, Endpointconfig ec) { } @0nClose public void onClose(Session session, CloseReason reason) { } @0nMessage public void receiveMessage(String message, Session session) { } @0nError public void onEr'r'or'(Throwable t) { } } Interconnect 2015 inbnumezconnect
  31. 31. Server Endpoint: Programmatic - Class extends Endpoint - Callback methods for lifecycle event notifications - Message notifications require a Me-ssageliandler public class ExtendedEndpoint extends Endpoint { @Override public void onOpen(Session session, Endpointconfig ec) { session. addMessageHandler‘(new MessageHandler. Whole<String>() { @Override public void onMessage(Str'ing message) { } }); } @Override public void onClose(Session session, CloseReason reason) { } @Override public void onError(Session session, Throwable t) { } Interconnect 2015 inbnumezconnect
  32. 32. Simple echo + server provided data (using annotations) - @Onl/ lessaqe method is called when a message is receive - If message is ‘stop’: close the session - Otherwise, echo the message along with a hit count int count = 0; @OnMessage public void receiveMessage(String message, Session session) throws IOException { if ( "stop". equals(message) ) { session. close(); } else { int id = count++; for (Session 5 : session. get0penSessions() ) { s. getBasicRemote(). sendText("Echo " + id + "2 " + message); } } } - Broadcast — iterate over open sessions InterConnect 201 5 Ifibmintexconnect
  33. 33. lnvocation. . what happens? - Let's see! Interconnect 2015 - - ittbmlrxterconnect
  34. 34. Encoder/ Decoder: dealing with data - Messages can be in text or binary format - Encoders and Decoders translate between data on the socket and Java Objects @ServerEndpoint(value = "/ EchoEncoderEndpoint", decoders = EchoDecoder. class, encoders = EchoEncoder. class) public class EchoEncoderEndpoint { @0nMessage public void receiveMessage(Echo0bject 0, Session session) throws IOException, EncodeException { if (o. stopRequest() ) { session . close(); } else { for (Session 5 : session. get0penSessions() ) { s. getBasicRemote(). send0bject(o); } } } Interconnect 2015 - inbmimexconnect
  35. 35. I-' -i: ilCOC. ‘7C: i" tiiee ing witii (;3:3::3 public class EchoEncoder implements Encoder. Text<Echo0bject> { J 0 @'Override public String encode(Echo0bject o) throws EncodeException { System. out. println( "Encoding " + o)' . . return mtostringo; ’ sendObject(Object data) } "é.1"Override public void init(EndpointConfig ec) {} -‘§JOverridc public void destroy() {} } : Encoder yes I for Object? No encoder. encode(Object) send message Interconnect iiibminterconnect
  36. 36. Decoder: dealing with data public class EchoDecoder implements Decoder. Text<Echo0bject> { @0verride public Echoobject decode(String msg) throws DecodeException { Echoobject 0; try { o = new Echo0bject(msg); read Message } catch(Exception e) { o = new Echo0bject(e); } System. out. pr'intln( "Decoded " + msg + " -> " + 0); return 0; } T gjoverride ext Decoder for Endpoint? public boolean willDecode(String msg) { return true; } @0verride. _ _ _ _ public void 1n1t(Endpo1ntConfig ec) {} decoder deCode(S, mng) @Override public void destroy() {} @OnMessage (Object) Interconnect 2015 — iribminterconnect
  37. 37. f— -; :cl1oObjccL public class EchoObject { / /J static final Atomiclnteger count = new Atomiclhtegerfi); (3 final Jsonobject obj; public Ec5oO5jectZString msg) 7f JsonReader r = Json. createReader(new StringReader(msg)); Jsonobject in = r. read0bject(); Json0bjectBuilder b = Json. create0bjectBuiZder(); b. add("count", count. getAndIncrementC)); b. add("content", in. getString("content", "none provided”)); obj = b. build(); public String toString() { return obj. toString(); } public Echo0bject(Exception e) { Json0bjectBuilder b = Json. create0bjectBuilder(); b. add("content", e. toString()); b. add("count", -1); obj = b. build(); encode decode } public boolean stopRequest() { return "stop". equals(obj. getString("content")); } } Interconnect , iiibminterconnect
  38. 38. ii‘l“~"'C)CC". lOl‘l. '~ wig l": :;>; ;:»: :.1s’? Let's see! Interconnect iiibminterconnect
  39. 39. 0 WebSockets have everything this application needs. - Why wouldn’t you use them? 0 - Older devices / browsers don’t support WebSockets - May be a challenge to degrade gracefully so older devices still have a decent experience - Trouble with proxies. . - wss: // recommended over ws: // - Some proxy servers do not inspect encrypted traffic: just pass through Interconnect O 1 5 Itibminterconnect
  40. 40. Challenges for Proxy servers - WebSocket protocol is unaware of proxies / firewalls - Relies on Upgrade header: - Hop-by-Hop Upgrade — Proxy server sends the request to the next hop — Upgrade header is only good for one link - Proxy servers required to strip certain headers when forwarding - Some load balancers also mangle the Connection header - HTTP CONNECT - Proxy to fon/ vard the TCP Connection to the destination - Some proxies still analyze traffic: would choke on websocket frame - SSL tunnelling has a better shot: — Some proxies restrict CONNECT to SSL — BUT: SSL termination. .. Inter Connect 2 C l Ilibminterconnect
  41. 41. WebSockets for Rich Clients - Java API for a rich Client is similar to API for Server - Annotations: @ClientEndpoint public class Annotatedclient { @0nOpen public void onOpen(Session session, Endpointtonfig ec) { } @0nClose public void onC1ose(Session session, CloseReason reason) { } @0nMessage public void processMessageFromServer(String message, Session session) { System. out. println("Message came from the server I " + message); } @0nError public void onError(Throwable t) { } Interconnect 2015 5 ltibmintarconnect
  42. 42. WebSockets for Rich Clients - Java API for a rich Client is similar to API for Server - Programmatic: final WebSocketContainer webSocketContoiner - ContainerProvider. getfleb$ocketContainer(); Session session - websocketcontainer. connectToServer(new Endpoint() { @0verride public void onOpen(Session session, EndpointConfig config) { session. addMessageHandler(new Messageflandler. Whole<String>() { @Override public void onMessage(String E) { System. out. println("Message came from the server I " + message); } D: } }, URI. create(“ws: //some. uri")); Interconnect 2015 itibminterconnect
  43. 43. iflbmmtetconnect O. Liestioi1s? liiif: ei*n: 201 5 The Premier Cloud & Mobile Conference
  44. 44. Notices and Disclaimers 3 Copyright © 2015 by lntemational Business Machines Corporation (IBM). No part of this document may be reproduced or transmitted in any form without written pemiission from IBM. U. S. Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM. Information in these presentations (including infonnation relating to products that have not yet been announced by IBM) has been reviewed for accuracy as of the date of initial publication and could include unintentional technical or typographical errors. IBM shall have no responsibility to update this information. THIS DOCUMENT IS DISTRIBUTED "AS IS" WITHOUT ANY WARRANTY, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL IBM BE LIABLE FOR ANY DAMAGE ARISING FROM THE USE OF THIS INFORMATION, INCLUDING BUT NOT LIMITED TO, LOSS OF DATA, BUSINESS INTERRUPTION, LOSS OF PROFIT OR LOSS OF OPPORTUNITY. IBM products and services are warranted according to the terms and conditions of the agreements under which they are provided. Any statements regarding IBM's future direction, intent or product plans are subject to change or withdrawal without notice. Performance data contained herein was generally obtained in a controlled, isolated environments. Customer examples are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual performance, cost, savings or other results in other operating environments may vary. References in this document to IBM products, programs, or services does not imply that IBM intends to make such products, programs or services available in all countries in which IBM operates or does business. Workshops, sessions and associated materials may have been prepared by independent session speakers, and do not necessarily reflect the views of IBM. All materials and discussions are provided for informational purposes only, and are neither intended to, nor shall constitute legal or other guidance or advice to any individual participant or their specific situation. It is the customer's responsibility to insure its own compliance with legal requirements and to obtain advice of competent legal counsel as to the identification and interpretation of any relevant laws and regulatory requirements that may affect the customer's business and any actions the customer may need to take to comply with such laws. IBM does not provide legal advice or represent or warrant that its services or products will ensure that the customer is in compliance with any law. Interconnect 20 l 5 Itibminterconnect
  45. 45. Notices and Disclaimers (con't) Information conceming non-IBM products was obtained from the suppliers of those products, their published announcements or other publicly available sources. IBM has not tested those products in connection with this publication and cannot confirm the accuracy of perfonnance, compatibility or any other claims related to non-IBM products. Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products. IBM does not warrant the quality of any third-party products, or the ability of any such third-party products to interoperate with IBM's products. IBM EXPRESSLY DISCLAIMS ALL WARRANTIES, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The provision of the information contained herein is not intended to, and does not, grant any right or license under any IBM patents, copyrights, trademarks or other intellectual property right. - IBM, the IBM logo, ibm. com, Bluemix, Blueworks Live, CICS, Clearcase, DOORS®, Enterprise Document Management System”, Global Business Services ®. Global Technology Services ®, Information on Demand, ILOG. Maximo®, MQlntegrator®, MQSeries®, Netcool®, OMEGAMON, OpenPower, PureAnalytics““, PureApplication®, pureclusterm, PureCoverage®, PureData®, PureExperience®, PureFlex®, pureQuery®, pureScale®, PureSystems®. QRadar®, Rational®, Rhapsody®, SoDA, SPSS, StoredlQ. TIVOlI®, Trusteer®, urban(code}®, Watson, WebSphere®, Worklight®, X-Force® and System z® Z/ OS, are trademarks of International Business Machines Corporation, registered in many jurisdictions worldwide. Other product and service names might be trademarks of IBM or other companies. A current list of IBM trademarks is available on the Web at "Copyright and trademark information" at: www. ibmcomllegallcopflrade. shtrnl. Interconnect 2015 ltibmimerconnect
  46. 46. Thank You Your Feedback is Important! Access the Interconnect 2015 Conference CONNECT Attendee Portal to complete your session surveys from your smartphone, laptop or conference kiosk. Interconnect 2015 he Premier Cloud & Mobile Conference

×