Building WebSocket and Server Side Events Applications using Atmosphere

5,553 views
5,228 views

Published on

An introduction to WebSocket and Server Side Events using the Atmosphee Framework

Published in: Technology
1 Comment
4 Likes
Statistics
Notes
No Downloads
Views
Total views
5,553
On SlideShare
0
From Embeds
0
Number of Embeds
47
Actions
Shares
0
Downloads
50
Comments
1
Likes
4
Embeds 0
No embeds

No notes for slide

Building WebSocket and Server Side Events Applications using Atmosphere

  1. 1. Building WebSocket and Server Side Events application using Atmosphere JeanfrancoisArcand twitter.com/jfarcand facebook.com/jeanfrancois.arcand.3
  2. 2. Who I am? Author ofAuthor of Grizzly GlassFish Micro Framework Kernel Author of AHC HTTP/WebSocket library Author of Atmosphere 10 years @ Sun Microsystems
  3. 3. AtmosphereApache 2 Github ~900 « followers » Client + Supported server by25frameworks Scala, Groovy, JRuby, Java Depuis 60 000 unique 2008 download per months 1.0.9 / 1.1.beta2
  4. 4. AtmosphereApache 2 Github ~900 ~1000 followers » « followerson Client + Supported Twitter server by25frameworks Scala, Groovy, ~400 users JRuby, Java mailing list Depuis 60 000 unique 2008 download per months 1.0.9 / 1.1.beta2
  5. 5. WebSocketsWebSocket: A Socket, that’sit!
  6. 6. Conclusion
  7. 7. WebSocketsWebSocket is a web technologyproviding full-duplexcommunications channels over asingle TCP connection. TheWebSocket API is beingstandardized by the W3C, and theWebSocket protocol has beenstandardized by the IETF as RFC6455.
  8. 8. WARNING!!Nobody is/will/was firedbecause of long-polling!!!
  9. 9. Polling Long Polling StreamingBrowser Server Browser Server Browser Server request request request empty response event event event response event response part request event event request response response part response request Browser Server request WebSocket => event Response event response
  10. 10. WebSockets HTML5Bi-directional
  11. 11. WebSockets HTML5Bi-directional Proxy/Fire wall
  12. 12. WebSockets HTML5Bi-directional Proxy/Fire wall « Less network overhead »
  13. 13. WebSockets HTML5Bi-directional Proxy/Fire wall « Less network overhead » Faster
  14. 14. WebSockets HTML5Bi-directional Proxy/Fire wall « Less network overhead » Faster SubProtocthan Ajax ol
  15. 15. WebSockets Real time appsPresence Collaboratio nNotification Anything!
  16. 16. First requestT 127.0.0.1:65062 -> 127.0.0.1:8080 [AP]GET / HTTP/1.1.Upgrade: websocket.Connection: Upgrade.Host: 127.0.0.1:8080.Origin: http://127.0.0.1:8080.Sec-WebSocket-Key: Tz9qdt3lmte6Slf+GvpRqQ==.Sec-WebSocket-Version: 13.Sec-WebSocket-Extensions: x-webkit-deflate-frame.
  17. 17. Second RequestT 127.0.0.1:8080 -> 127.0.0.1:51292 [AP]HTTP/1.1 101 Switching Protocols.Upgrade: WebSocket.Connection: Upgrade.Sec-WebSocket-Accept:HVXA7SqH5uYeN6aD9tZ0JQbfTJA=.
  18. 18. Life if good!T 127.0.0.1:8080 -> 127.0.0.1:51292 [AP]HTTP/1.1 101 Switching Protocols.Upgrade: WebSocket.Connection: Upgrade.Sec-WebSocket-Accept:HVXA7SqH5uYeN6aD9tZ0JQbfTJA=.
  19. 19. OUPS!!!T 127.0.0.1:8080 -> 127.0.0.1:65064 [AP]HTTP/1.1 501 Not Implemented.Server: Apache-Coyote/1.1.X-Atmosphere-error: Websocket protocol notsupported.Transfer-Encoding: chunked.Date: Fri, 15 Jun 2012 10:06:30 GMT.Connection: close..
  20. 20. OUPS!!!T 127.0.0.1:8080 -> 127.0.0.1:65064 [AP]HTTP/1.1 501 Not Implemented.Server: Apache-Coyote/1.1. AtmosphereX-Atmosphere-error: Websocket protocol notsupported. to theTransfer-Encoding: chunked. rescueDate: Fri, 15 Jun 2012 10:06:30 GMT.Connection: close..
  21. 21. WebSocket API – Standard JavaScriptwebsocket = new WebSocket(wsUri);websocket.onopen= function(evt) { …};websocket.onclose= function(evt) { …};websocket.onmessage= function(evt) { …};websocket.onerror= function(evt) { …};webSocket.send(…)
  22. 22. Server – No Standard yet• Node.js• Pusher• Jetty• GlassFish• Tomcat• Apache• NIO Framework like Netty and Grizzly
  23. 23. WebSocket API – JavaJetty 7, GlassFish 3.1, Netty 3, Tomcat7.0.27, Resin 4, JBoss 7JSR 356:http://jcp.org/en/jsr/detail?id=356AHC (Client -> De facto)http://github.com/sonatype/async-http-client
  24. 24. WebSocket API – Java &ScalawAsync:https://github.com/Atmosphere/wasyncSwaggerSocket (REST overWebSocket)https://github.com/wordnik/swaggersocket
  25. 25. WARNING!Y’en aura pas de facile!!!
  26. 26. Before (Long-Polling) RequestBrowse Server r
  27. 27. Before (Long-Polling) RequestBrowse Server r
  28. 28. Before (Long-Polling) RequestBrowse Server r Response
  29. 29. Oups!! RequestBrowse zzzz Server r
  30. 30. Oups! RequestBrowse Server r Zzzz
  31. 31. Better! RequestBrowse Server r Cache
  32. 32. Better! RequestBrowse Server r Cache
  33. 33. Pushing the limits (HTTP Streaming) Request Browse Server r
  34. 34. Pushing the limits (HTTP Streaming) Request Browse Server r
  35. 35. Pushing the limits (HTTP Streaming) Request Browse Server r Response
  36. 36. Pushing the limits (HTTP Streaming) Request Browse Server r Response Response
  37. 37. Oups!! RequestBrowse Server r Response JS HELL Response
  38. 38. Pushing the limits (HTTP Streaming) Request Browse Server r L’enfe Hack Response r Response
  39. 39. Oups!!! RequestBrowse Server r Response Proxy Response
  40. 40. Better RequestBrowse Server r Response Cache Response
  41. 41. Better RequestBrowse Server r Response Cache « HeartBeat Response »
  42. 42. Better: Server Side Events (SSE) RequestBrowse Server r Response Response
  43. 43. Oups!!! RequestBrowse Server r Response Proxy Response
  44. 44. Better RequestBrowse Server r Response Cache « HeartBeat Response »
  45. 45. Better RequestBrowse Not Supported Server r by Internet Response Cache Explorer « HeartBeat Response »
  46. 46. WebSockets HanshakeBrowse Server r
  47. 47. WebSockets HanshakeBrowse Server r OK
  48. 48. WebSockets RequestBrowse Server r
  49. 49. WebSockets RequestBrowse Server r
  50. 50. WebSocketsBrowse Server r Response
  51. 51. WebSockets RequestBrowse Server r
  52. 52. WebSockets Request RequestBrowse Server r
  53. 53. WebSockets Request RequestBrowse Server r
  54. 54. WebSocketsBrowse Server r Response Response
  55. 55. AnytimeBrowse Server r Response
  56. 56. Ah la belle vie, la vie, la vie ahah!Browse Server r Response
  57. 57. Oups!!Browse Server r Proxy Response
  58. 58. Better!Browse Server r Response Cache
  59. 59. Better!Browse Server r Response Cache « HeartBeat »
  60. 60. Ah la belle vie,la vie, la vie, ahah
  61. 61. OUPS!!!
  62. 62. Go!!Safari Tomcat 7Firefox Jetty7 Jetty8Chrome GlassFisOpera h3. GlassFis IE h 312
  63. 63. Free for all!Safari Tomcat 7Firefox Jetty7 Jetty8Chrome GlassFisOpera h3. GlassFis IE h 312
  64. 64. Free for all!Safari Tomcat 7Firefox Jetty7 HELP Jetty8Chrome GlassFisOpera h3. GlassFis IE h 312
  65. 65. Free for all!Safari Tomcat 7 Streamin Jetty7Firefox g Au Jetty8Chrome Secours GlassFisOpera !! h3. GlassFis IE h 312
  66. 66. Free for all!Safari Tomcat 7 Streamin Jetty7Firefox g Au SSE Jetty8Chrome Secours GlassFisOpera !! h3. GlassFis IE h 312
  67. 67. Free for all!Safari Tomcat 7 Streamin Jetty7Firefox g Au SSE Jetty8Chrome Secours GlassFisOpera !! JSONP h3. GlassFis IE h 312
  68. 68. Free for all!Safari Tomcat 7 Streamin Jetty7Firefox g Au SSE Jetty8Chrome Secours GlassFis Opera !! JSONP h3. Long GlassFis IE Polling h 312
  69. 69. Safari Tomcat 7Firefox Jetty7 AtmosphereChrome to the Jetty8 rescue!!! GlassFisOpera h3. GlassFis IE h 312
  70. 70. Atmosphere -WebSocketsSafari Tomcat 7 Jetty7 Atmosphere APIFirefox atmosphere.js Jetty8Chrome GlassFisOpera h3. GlassFis IE h 312
  71. 71. Atmosphere - HTML5 Server Side EventsSafari Tomcat 7 Jetty7 Atmosphere APIFirefox atmosphere.js ServletChrome 3 WebLogiOpera c GlassFis IE h 312
  72. 72. Atmosphere Long-Polling/HTTP StreamingSafari JBoss Jetty7 Atmosphere APIFirefox atmosphere.js ServletChrome 3 WebLogiOpera c. GlassFis IE h
  73. 73. AtmosphereSafari JBoss Jetty7 Atmosphere APIFirefox atmosphere.js One API toChrome rule them all Servlet 3 WebLogiOpera c. GlassFis IE h
  74. 74. Socket.IO, GWT, Wicket, JSF, etc.Safari JBoss Jetty7 Atmosphere APIFirefox Socket.IO ServletChrome 3 WebLogiOpera c. GlassFis IE h
  75. 75. PORTABLE!!!!!Safari JBoss Jetty7 Atmosphere APIFirefox Socket.IO PORTABLE ServletChrome 3 WebLogiOpera c. GlassFis IE h
  76. 76. Big Mistake!!!!!• Thereare still a lot of dinosaur in the wilderness! Deploy in Production impossible
  77. 77. Demo
  78. 78. AtmosphereHandlerpublic interface AtmosphereHandler {void onRequest(AtmosphereResource resource) throws IOException;void onStateChange(AtmosphereResourceEvent event) throws IOException;void destroy();}
  79. 79. AtmosphereHandlerpublic class ChatAtmosphereHandler implements AtmosphereHandler { @Override public void onRequest(AtmosphereResource r) throws IOException { AtmosphereRequest req = r.getRequest(); if (req.getMethod().equalsIgnoreCase("GET")) {r.suspend(); } else if (req.getMethod().equalsIgnoreCase("POST")) { r.getBroadcaster().broadcast(req.getReader().readLine().trim()); } }
  80. 80. AtmosphereHandlerpublic void onStateChange(AtmosphereResourceEvent event) throws IOException { …. if (event.isSuspended()) { … res.getWriter().write(new Data(author, message).toString()); switch (r.transport()) { case JSONP: case AJAX: case LONG_POLLING: event.getResource().resume(); break; case WEBSOCKET : case STREAMING: res.getWriter().flush(); break; } } else if (!event.isResuming()){ event.broadcaster().broadcast(new Data("Someone", "say bye bye!").toString()); } }
  81. 81. OnMessage@AtmosphereHandlerService( path="/chat", interceptors = {AtmosphereResourceLifecycleInterceptor.class, BroadcastOnPostAtmosphereInterceptor.class}) public class ChatRoom extends OnMessage<String>{ private final ObjectMapper mapper = new ObjectMapper(); @Override public void onMessage(AtmosphereResponse response, String message) { response.getWriter() .write(mapper.writeValueAsString( mapper.readValue(message, Data.class))); } }
  82. 82. @Managed@ManagedAtmosphereHandlerService (path = "/chat")public class ChatAtmosphereHandler { private final ObjectMapper mapper = new ObjectMapper(); @Message public void onMessage(AtmosphereResponse response, String message) throws IOException { response.getWriter().write( mapper.writeValueAsString( mapper.readValue(message, Data.class))); }
  83. 83. @Managed are..@AtmosphereHandlerService( path = "/chat", broadcasterCache = HeaderBroadcasterCache.class,interceptors = { AtmosphereResourceLifecycleInterceptor.class, BroadcastOnPostAtmosphereInterceptor.class, TrackMessageSizeInterceptor.class, HeartbeatInterceptor.class})
  84. 84. Jersey@Path("/")public class ChatResource { @Suspend(contentType = "application/json") @GET public String suspend() { return ""; } @Broadcast(writeEntity = false) @POST @Produces("application/json") public Response broadcast(Message message) { return new Response(message.author, message.message); }}
  85. 85. Clientvar socket = $.atmosphere;var subSocket;var transport = websocket;var request = { url: document.location.toString() + chat, contentType : "application/json", logLevel : debug, shared : true, transport : transport , trackMessageLength : true, fallbackTransport: long-polling};
  86. 86. Clientrequest.onOpen = function(response) { };request.onTransportFailure = function(errorMsg, request) { };request.onReconnect = function (request, response) { };request.onMessage = function (response) { };request.onClose = function(response) { }request.onError = function(response) { };subSocket = socket.subscribe(request);
  87. 87. ClientsubSocket.push(….);
  88. 88. Broadcaster• Default: in-memory• Cloud • RedisBroadcaster • JMSBroadcaster • XMPPBroadcaster • HazelcastBroadcaster • JGroupsBroascaster• Multi-Threads, Async I/O par default
  89. 89. Broadcaster
  90. 90. Atmosphere Components• WebSocketHandler • Only WebSocket (WARNING)!• AtmosphereHandler • All transports• Jersey Resource • All transports• Meteor • All transports
  91. 91. Démo
  92. 92. WebSocket Sub Protocol• WebSocketProtocol Define your own protocol on top of WebSocket• Default: WebSocket message => POST• SwaggerSocket:REST over WebSockets -> More information
  93. 93. PLEASE HELPhttp://github.com/Atmosphere/atmosp here
  94. 94. twitter.com/jfarcand twitter.com/atmo_framework twitter.com/swaggersocket http://github.com/Atmosphere/http://github.com/wordnik/swaggersocket

×