SlideShare una empresa de Scribd logo
1 de 96
Building WebSocket and Server Side Events
        application using Atmosphere
              JeanfrancoisArcand

              twitter.com/jfarcand
       facebook.com/jeanfrancois.arcand.3
Who I am?
                       Author of
Author of Grizzly   GlassFish Micro
  Framework             Kernel
     Author of AHC
    HTTP/WebSocket
         library
           Author of
        Atmosphere
                     10 years @
                         Sun
                    Microsystems
Atmosphere

Apache 2      Github ~900
              « followers »
                              Client +
 Supported                    server
   by25
frameworks                    Scala, Groovy,
                               JRuby, Java
 Depuis
                   60 000 unique
  2008
                download per months
   1.0.9 /
 1.1.beta2
Atmosphere

Apache 2          Github ~900
             ~1000 followers »
                  «
          followerson           Client +
 Supported Twitter                server
    by25
frameworks                     Scala, Groovy,
                        ~400 users
                                JRuby, Java
                        mailing list
   Depuis
                        60 000 unique
    2008
                    download per months
    1.0.9 /
  1.1.beta2
WebSockets


WebSocket: A Socket, that’s
it!
Conclusion
WebSockets


WebSocket is a web technology
providing full-duplex
communications channels over a
single TCP connection. The
WebSocket API is being
standardized by the W3C, and the
WebSocket protocol has been
standardized by the IETF as RFC
6455.
WARNING!!
Nobody is/will/was fired
because of long-polling!!!
Polling                     Long Polling                      Streaming
Browser          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
WebSockets
                   HTML5

Bi-directional
WebSockets
                   HTML5

Bi-directional                Proxy/Fire
                                 wall
WebSockets
                   HTML5

Bi-directional                Proxy/Fire
                                 wall

             « Less network
               overhead »
WebSockets
                   HTML5

Bi-directional                Proxy/Fire
                                 wall

             « Less network
               overhead »

 Faster
WebSockets
                   HTML5

Bi-directional                Proxy/Fire
                                 wall

             « Less network
               overhead »

  Faster
                              SubProtoc
than Ajax
                                 ol
WebSockets

               Real time apps

Presence                        Collaboratio
                                     n



Notification                Anything!
First request
T 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.
Second Request
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=.
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=.
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 not
supported.
Transfer-Encoding: chunked.
Date: Fri, 15 Jun 2012 10:06:30 GMT.
Connection: close.
.
OUPS!!!
T 127.0.0.1:8080 -> 127.0.0.1:65064 [AP]
HTTP/1.1 501 Not Implemented.
Server: Apache-Coyote/1.1.
                Atmosphere
X-Atmosphere-error: Websocket protocol not
supported.
                       to the
Transfer-Encoding:   chunked.
                      rescue
Date: Fri, 15 Jun 2012 10:06:30 GMT.
Connection: close.
.
WebSocket API – Standard
           JavaScript
websocket = new WebSocket(wsUri);
websocket.onopen= function(evt) { …};
websocket.onclose= function(evt) { …};
websocket.onmessage= function(evt) { …};
websocket.onerror= function(evt) { …};


webSocket.send(…)
Server – No Standard yet

• Node.js
• Pusher
• Jetty
• GlassFish
• Tomcat
• Apache
• NIO Framework like Netty and Grizzly
WebSocket API – Java

Jetty 7, GlassFish 3.1, Netty 3, Tomcat
7.0.27, Resin 4, JBoss 7


JSR 356:
http://jcp.org/en/jsr/detail?id=356


AHC (Client -> De facto)
http://github.com/sonatype/async-http-
client
WebSocket API – Java &Scala


wAsync:
https://github.com/Atmosphere/wasync


SwaggerSocket (REST overWebSocket)
https://github.com/wordnik/swaggersock
et
WARNING!
Y’en aura pas de facile!!!
Before (Long-Polling)

           Request


Browse                       Server
   r
Before (Long-Polling)

           Request


Browse                       Server
   r
Before (Long-Polling)

           Request


Browse                       Server
   r
          Response
Oups!!


         Request

Browse        zzzz   Server
   r
Oups!

         Request


Browse             Server
   r
                   Zzzz
Better!


         Request

Browse                  Server
   r

                      Cache
Better!

         Request


Browse               Server
   r

                   Cache
Pushing the limits (HTTP Streaming)

             Request


 Browse                    Server
    r
Pushing the limits (HTTP Streaming)

             Request


 Browse                    Server
    r
Pushing the limits (HTTP Streaming)

             Request


 Browse                    Server
    r
            Response
Pushing the limits (HTTP Streaming)

             Request


 Browse                    Server
    r
            Response

            Response
Oups!!

         Request


Browse              Server
   r
         Response
   JS
  HELL   Response
Pushing the limits (HTTP Streaming)

             Request


 Browse                    Server
    r
   L’enfe
    Hack    Response
      r
            Response
Oups!!!

         Request


Browse              Server
   r
         Response
            Proxy
         Response
Better

         Request


Browse                Server
   r
         Response Cache

         Response
Better

          Request


Browse                 Server
   r
         Response Cache
         « HeartBeat
         Response
              »
Better: Server Side Events (SSE)

            Request


Browse                    Server
   r
           Response

           Response
Oups!!!

         Request


Browse              Server
   r
         Response
            Proxy
         Response
Better

          Request


Browse                 Server
   r
         Response Cache
         « HeartBeat
         Response
              »
Better

          Request


Browse   Not Supported  Server
   r       by Internet
          Response Cache
            Explorer
         « HeartBeat
          Response
               »
WebSockets

          Hanshake


Browse                Server
   r
WebSockets

          Hanshake


Browse                Server
   r
            OK
WebSockets

          Request


Browse                Server
   r
WebSockets

          Request


Browse                Server
   r
WebSockets




Browse                Server
   r
         Response
WebSockets

          Request


Browse                Server
   r
WebSockets

          Request

           Request
Browse                Server
   r
WebSockets

          Request

           Request
Browse                Server
   r
WebSockets




Browse                Server
   r
         Response

         Response
Anytime




Browse              Server
   r
         Response
Ah la belle vie, la vie, la vie ahah!




Browse                        Server
   r
            Response
Oups!!




Browse              Server
   r        Proxy
         Response
Better!




Browse                Server
   r
         Response Cache
Better!




Browse                 Server
   r
         Response Cache
         « HeartBeat
              »
Ah la belle vie,
la vie, la vie, ahah
OUPS!!!
Go!!
Safari           Tomcat
                    7
Firefox          Jetty7

                  Jetty8
Chrome

                 GlassFis
Opera              h3.
                 GlassFis
  IE                h
                   312
Free for all!
Safari                    Tomcat
                             7
Firefox                   Jetty7

                           Jetty8
Chrome

                          GlassFis
Opera                       h3.
                          GlassFis
  IE                         h
                            312
Free for all!
Safari                    Tomcat
                             7
Firefox                   Jetty7

          HELP             Jetty8
Chrome

                          GlassFis
Opera                       h3.
                          GlassFis
  IE                         h
                            312
Free for all!
Safari                         Tomcat
                                  7
          Streamin             Jetty7
Firefox
              g
                  Au            Jetty8
Chrome
                Secours
                               GlassFis
Opera              !!            h3.
                               GlassFis
  IE                              h
                                 312
Free for all!
Safari                        Tomcat
                                 7
          Streamin            Jetty7
Firefox
              g
                  Au SSE       Jetty8
Chrome
                Secours
                              GlassFis
Opera              !!           h3.
                              GlassFis
  IE                             h
                                312
Free for all!
Safari                         Tomcat
                                  7
          Streamin             Jetty7
Firefox
              g
                  Au SSE   Jetty8
Chrome
                Secours
                          GlassFis
Opera              !!   JSONP
                            h3.
                               GlassFis
  IE                              h
                                 312
Free for all!
Safari                             Tomcat
                                      7
        Streamin                   Jetty7
Firefox
            g
                Au SSE   Jetty8
Chrome
              Secours
                        GlassFis
 Opera           !!   JSONP
                          h3.
        Long
                                   GlassFis
  IE     Polling                      h
                                     312
Safari                 Tomcat
                          7
Firefox                Jetty7
          Atmosphere
Chrome       to the     Jetty8

           rescue!!!   GlassFis
Opera                    h3.
                       GlassFis
  IE                      h
                         312
Atmosphere -WebSockets

Safari                                        Tomcat
                                                 7
                                              Jetty7




                             Atmosphere API
Firefox
             atmosphere.js
                                               Jetty8
Chrome

                                              GlassFis
Opera                                           h3.
                                              GlassFis
  IE                                             h
                                                312
Atmosphere - HTML5 Server Side
               Events
Safari                                     Tomcat
                                              7
                                           Jetty7




                          Atmosphere API
Firefox
          atmosphere.js
                                           Servlet
Chrome
                                             3
                                           WebLogi
Opera                                        c
                                           GlassFis
  IE                                          h
                                             312
Atmosphere Long-Polling/HTTP
                Streaming
Safari                                        JBoss

                                              Jetty7




                            Atmosphere API
Firefox
            atmosphere.js
                                             Servlet
Chrome
                                               3
                                             WebLogi
Opera                                          c.
                                             GlassFis
  IE                                            h
Atmosphere

Safari                                                   JBoss

                                                         Jetty7




                                       Atmosphere API
Firefox
          atmosphere.js
                 One API to
Chrome          rule them all                           Servlet
                                                          3
                                                        WebLogi
Opera                                                     c.
                                                        GlassFis
  IE                                                       h
Socket.IO, GWT, Wicket, JSF, etc.

Safari                                     JBoss

                                           Jetty7




                         Atmosphere API
Firefox
          Socket.IO
                                          Servlet
Chrome
                                            3
                                          WebLogi
Opera                                       c.
                                          GlassFis
  IE                                         h
PORTABLE!!!!!

Safari                                             JBoss

                                                   Jetty7




                                 Atmosphere API
Firefox
          Socket.IO
                      PORTABLE                    Servlet
Chrome
                                                    3
                                                  WebLogi
Opera                                               c.
                                                  GlassFis
  IE                                                 h
Big Mistake!!!!!

• Thereare still a lot of
 dinosaur in the wilderness!



     Deploy in
    Production
    impossible
Demo
AtmosphereHandler
public interface AtmosphereHandler {


void onRequest(AtmosphereResource resource)
     throws IOException;


void onStateChange(AtmosphereResourceEvent
    event) throws IOException;


void destroy();
}
AtmosphereHandler
public 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());
       }
   }
AtmosphereHandler

public 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());

            }

   }
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)));

     }

 }
@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)));
   }
@Managed are..
@AtmosphereHandlerService(

  path = "/chat",
  broadcasterCache =
           HeaderBroadcasterCache.class,
interceptors = {
  AtmosphereResourceLifecycleInterceptor.class,
   BroadcastOnPostAtmosphereInterceptor.class,
   TrackMessageSizeInterceptor.class,
   HeartbeatInterceptor.class})
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);

    }



}
Client
var 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'};
Client
request.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);
Client




subSocket.push(….);
Broadcaster

• Default:    in-memory
• Cloud
 •   RedisBroadcaster
 •   JMSBroadcaster
 •   XMPPBroadcaster
 •   HazelcastBroadcaster
 •   JGroupsBroascaster
• Multi-Threads,        Async I/O par
 default
Broadcaster
Atmosphere Components

• WebSocketHandler
 •   Only WebSocket (WARNING)!
• AtmosphereHandler
 •   All transports
• Jersey   Resource
 •   All transports
• Meteor
 •   All transports
Démo
WebSocket Sub Protocol

• WebSocketProtocol
 Define your own protocol on top of
 WebSocket


• Default:
   WebSocket message => POST
• SwaggerSocket:REST over
 WebSockets -> More information
PLEASE HELP
http://github.com/Atmosphere/atmosp
                 here
twitter.com/jfarcand
      twitter.com/atmo_framework
       twitter.com/swaggersocket

     http://github.com/Atmosphere/

http://github.com/wordnik/swaggersocket

Más contenido relacionado

La actualidad más candente

Spring Boot & WebSocket
Spring Boot & WebSocketSpring Boot & WebSocket
Spring Boot & WebSocket
Ming-Ying Wu
 

La actualidad más candente (20)

Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
Building Real-Time Applications with Android and WebSockets
Building Real-Time Applications with Android and WebSocketsBuilding Real-Time Applications with Android and WebSockets
Building Real-Time Applications with Android and WebSockets
 
Ruby Proxies for Scale, Performance, and Monitoring
Ruby Proxies for Scale, Performance, and MonitoringRuby Proxies for Scale, Performance, and Monitoring
Ruby Proxies for Scale, Performance, and Monitoring
 
Event Driven Architecture - MeshU - Ilya Grigorik
Event Driven Architecture - MeshU - Ilya GrigorikEvent Driven Architecture - MeshU - Ilya Grigorik
Event Driven Architecture - MeshU - Ilya Grigorik
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
 
Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
 
Solving anything in VCL
Solving anything in VCLSolving anything in VCL
Solving anything in VCL
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
Speedy TDD with Rails
Speedy TDD with RailsSpeedy TDD with Rails
Speedy TDD with Rails
 
Ws
WsWs
Ws
 
Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with java
 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in JavaGetting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
 
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
 
Spring Boot & WebSocket
Spring Boot & WebSocketSpring Boot & WebSocket
Spring Boot & WebSocket
 

Similar a Building WebSocket and Server Side Events Applications using Atmosphere

WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
Viktor Gamov
 
Do we still need a web framework ?
Do we still need a web framework ?Do we still need a web framework ?
Do we still need a web framework ?
Mathieu Carbou
 
As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?
ConFoo
 
Pushing the web — WebSockets
Pushing the web — WebSocketsPushing the web — WebSockets
Pushing the web — WebSockets
Roland M
 

Similar a Building WebSocket and Server Side Events Applications using Atmosphere (20)

Connected Web Systems
Connected Web SystemsConnected Web Systems
Connected Web Systems
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
 
Server-Side Programming Primer
Server-Side Programming PrimerServer-Side Programming Primer
Server-Side Programming Primer
 
Web-Socket
Web-SocketWeb-Socket
Web-Socket
 
Do we still need a web framework ?
Do we still need a web framework ?Do we still need a web framework ?
Do we still need a web framework ?
 
As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?
 
Pushing the web — WebSockets
Pushing the web — WebSocketsPushing the web — WebSockets
Pushing the web — WebSockets
 
Building real-time-collaborative-web-applications
Building real-time-collaborative-web-applicationsBuilding real-time-collaborative-web-applications
Building real-time-collaborative-web-applications
 
Toster - Understanding the Rails Web Model and Scalability Options
Toster - Understanding the Rails Web Model and Scalability OptionsToster - Understanding the Rails Web Model and Scalability Options
Toster - Understanding the Rails Web Model and Scalability Options
 
Understanding the Rails web model and scalability options
Understanding the Rails web model and scalability optionsUnderstanding the Rails web model and scalability options
Understanding the Rails web model and scalability options
 
Html5 security
Html5 securityHtml5 security
Html5 security
 
Webinar slides "Building Real-Time Collaborative Web Applications"
Webinar slides "Building Real-Time Collaborative Web Applications"Webinar slides "Building Real-Time Collaborative Web Applications"
Webinar slides "Building Real-Time Collaborative Web Applications"
 
WebSocket protocol
WebSocket protocolWebSocket protocol
WebSocket protocol
 
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at ScaleJUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
 
Websocket vs SSE - Paris.js - 24/06/15
Websocket vs SSE - Paris.js - 24/06/15Websocket vs SSE - Paris.js - 24/06/15
Websocket vs SSE - Paris.js - 24/06/15
 
Realtime Streaming using Autobahn Websockets
Realtime Streaming using Autobahn WebsocketsRealtime Streaming using Autobahn Websockets
Realtime Streaming using Autobahn Websockets
 
Deployment de Rails
Deployment de RailsDeployment de Rails
Deployment de Rails
 
vert.x - asynchronous event-driven web applications on the JVM
vert.x - asynchronous event-driven web applications on the JVMvert.x - asynchronous event-driven web applications on the JVM
vert.x - asynchronous event-driven web applications on the JVM
 
Realtime Web 간보기
Realtime Web 간보기Realtime Web 간보기
Realtime Web 간보기
 
Evolving Archetecture
Evolving ArchetectureEvolving Archetecture
Evolving Archetecture
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Building WebSocket and Server Side Events Applications using Atmosphere

  • 1. Building WebSocket and Server Side Events application using Atmosphere JeanfrancoisArcand twitter.com/jfarcand facebook.com/jeanfrancois.arcand.3
  • 2. Who I am? Author of Author of Grizzly GlassFish Micro Framework Kernel Author of AHC HTTP/WebSocket library Author of Atmosphere 10 years @ Sun Microsystems
  • 3. Atmosphere Apache 2 Github ~900 « followers » Client + Supported server by25 frameworks Scala, Groovy, JRuby, Java Depuis 60 000 unique 2008 download per months 1.0.9 / 1.1.beta2
  • 4. Atmosphere Apache 2 Github ~900 ~1000 followers » « followerson Client + Supported Twitter server by25 frameworks Scala, Groovy, ~400 users JRuby, Java mailing list Depuis 60 000 unique 2008 download per months 1.0.9 / 1.1.beta2
  • 7. WebSockets WebSocket is a web technology providing full-duplex communications channels over a single TCP connection. The WebSocket API is being standardized by the W3C, and the WebSocket protocol has been standardized by the IETF as RFC 6455.
  • 9. Polling Long Polling Streaming Browser 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. WebSockets HTML5 Bi-directional
  • 11. WebSockets HTML5 Bi-directional Proxy/Fire wall
  • 12. WebSockets HTML5 Bi-directional Proxy/Fire wall « Less network overhead »
  • 13. WebSockets HTML5 Bi-directional Proxy/Fire wall « Less network overhead » Faster
  • 14. WebSockets HTML5 Bi-directional Proxy/Fire wall « Less network overhead » Faster SubProtoc than Ajax ol
  • 15. WebSockets Real time apps Presence Collaboratio n Notification Anything!
  • 16. First request T 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. Second Request 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=.
  • 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. 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 not supported. Transfer-Encoding: chunked. Date: Fri, 15 Jun 2012 10:06:30 GMT. Connection: close. .
  • 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. Atmosphere X-Atmosphere-error: Websocket protocol not supported. to the Transfer-Encoding: chunked. rescue Date: Fri, 15 Jun 2012 10:06:30 GMT. Connection: close. .
  • 21. WebSocket API – Standard JavaScript websocket = new WebSocket(wsUri); websocket.onopen= function(evt) { …}; websocket.onclose= function(evt) { …}; websocket.onmessage= function(evt) { …}; websocket.onerror= function(evt) { …}; webSocket.send(…)
  • 22. Server – No Standard yet • Node.js • Pusher • Jetty • GlassFish • Tomcat • Apache • NIO Framework like Netty and Grizzly
  • 23. WebSocket API – Java Jetty 7, GlassFish 3.1, Netty 3, Tomcat 7.0.27, Resin 4, JBoss 7 JSR 356: http://jcp.org/en/jsr/detail?id=356 AHC (Client -> De facto) http://github.com/sonatype/async-http- client
  • 24. WebSocket API – Java &Scala wAsync: https://github.com/Atmosphere/wasync SwaggerSocket (REST overWebSocket) https://github.com/wordnik/swaggersock et
  • 25. WARNING! Y’en aura pas de facile!!!
  • 26. Before (Long-Polling) Request Browse Server r
  • 27. Before (Long-Polling) Request Browse Server r
  • 28. Before (Long-Polling) Request Browse Server r Response
  • 29. Oups!! Request Browse zzzz Server r
  • 30. Oups! Request Browse Server r Zzzz
  • 31. Better! Request Browse Server r Cache
  • 32. Better! Request Browse Server r Cache
  • 33. Pushing the limits (HTTP Streaming) Request Browse Server r
  • 34. Pushing the limits (HTTP Streaming) Request Browse Server r
  • 35. Pushing the limits (HTTP Streaming) Request Browse Server r Response
  • 36. Pushing the limits (HTTP Streaming) Request Browse Server r Response Response
  • 37. Oups!! Request Browse Server r Response JS HELL Response
  • 38. Pushing the limits (HTTP Streaming) Request Browse Server r L’enfe Hack Response r Response
  • 39. Oups!!! Request Browse Server r Response Proxy Response
  • 40. Better Request Browse Server r Response Cache Response
  • 41. Better Request Browse Server r Response Cache « HeartBeat Response »
  • 42. Better: Server Side Events (SSE) Request Browse Server r Response Response
  • 43. Oups!!! Request Browse Server r Response Proxy Response
  • 44. Better Request Browse Server r Response Cache « HeartBeat Response »
  • 45. Better Request Browse Not Supported Server r by Internet Response Cache Explorer « HeartBeat Response »
  • 46. WebSockets Hanshake Browse Server r
  • 47. WebSockets Hanshake Browse Server r OK
  • 48. WebSockets Request Browse Server r
  • 49. WebSockets Request Browse Server r
  • 50. WebSockets Browse Server r Response
  • 51. WebSockets Request Browse Server r
  • 52. WebSockets Request Request Browse Server r
  • 53. WebSockets Request Request Browse Server r
  • 54. WebSockets Browse Server r Response Response
  • 55. Anytime Browse Server r Response
  • 56. Ah la belle vie, la vie, la vie ahah! Browse Server r Response
  • 57. Oups!! Browse Server r Proxy Response
  • 58. Better! Browse Server r Response Cache
  • 59. Better! Browse Server r Response Cache « HeartBeat »
  • 60. Ah la belle vie, la vie, la vie, ahah
  • 62. Go!! Safari Tomcat 7 Firefox Jetty7 Jetty8 Chrome GlassFis Opera h3. GlassFis IE h 312
  • 63. Free for all! Safari Tomcat 7 Firefox Jetty7 Jetty8 Chrome GlassFis Opera h3. GlassFis IE h 312
  • 64. Free for all! Safari Tomcat 7 Firefox Jetty7 HELP Jetty8 Chrome GlassFis Opera h3. GlassFis IE h 312
  • 65. Free for all! Safari Tomcat 7 Streamin Jetty7 Firefox g Au Jetty8 Chrome Secours GlassFis Opera !! h3. GlassFis IE h 312
  • 66. Free for all! Safari Tomcat 7 Streamin Jetty7 Firefox g Au SSE Jetty8 Chrome Secours GlassFis Opera !! h3. GlassFis IE h 312
  • 67. Free for all! Safari Tomcat 7 Streamin Jetty7 Firefox g Au SSE Jetty8 Chrome Secours GlassFis Opera !! JSONP h3. GlassFis IE h 312
  • 68. Free for all! Safari Tomcat 7 Streamin Jetty7 Firefox g Au SSE Jetty8 Chrome Secours GlassFis Opera !! JSONP h3. Long GlassFis IE Polling h 312
  • 69. Safari Tomcat 7 Firefox Jetty7 Atmosphere Chrome to the Jetty8 rescue!!! GlassFis Opera h3. GlassFis IE h 312
  • 70. Atmosphere -WebSockets Safari Tomcat 7 Jetty7 Atmosphere API Firefox atmosphere.js Jetty8 Chrome GlassFis Opera h3. GlassFis IE h 312
  • 71. Atmosphere - HTML5 Server Side Events Safari Tomcat 7 Jetty7 Atmosphere API Firefox atmosphere.js Servlet Chrome 3 WebLogi Opera c GlassFis IE h 312
  • 72. Atmosphere Long-Polling/HTTP Streaming Safari JBoss Jetty7 Atmosphere API Firefox atmosphere.js Servlet Chrome 3 WebLogi Opera c. GlassFis IE h
  • 73. Atmosphere Safari JBoss Jetty7 Atmosphere API Firefox atmosphere.js One API to Chrome rule them all Servlet 3 WebLogi Opera c. GlassFis IE h
  • 74. Socket.IO, GWT, Wicket, JSF, etc. Safari JBoss Jetty7 Atmosphere API Firefox Socket.IO Servlet Chrome 3 WebLogi Opera c. GlassFis IE h
  • 75. PORTABLE!!!!! Safari JBoss Jetty7 Atmosphere API Firefox Socket.IO PORTABLE Servlet Chrome 3 WebLogi Opera c. GlassFis IE h
  • 76. Big Mistake!!!!! • Thereare still a lot of dinosaur in the wilderness! Deploy in Production impossible
  • 77. Demo
  • 78.
  • 79. AtmosphereHandler public interface AtmosphereHandler { void onRequest(AtmosphereResource resource) throws IOException; void onStateChange(AtmosphereResourceEvent event) throws IOException; void destroy(); }
  • 80. AtmosphereHandler public 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()); } }
  • 81. AtmosphereHandler public 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()); } }
  • 82. 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))); } }
  • 83. @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))); }
  • 84. @Managed are.. @AtmosphereHandlerService( path = "/chat", broadcasterCache = HeaderBroadcasterCache.class, interceptors = { AtmosphereResourceLifecycleInterceptor.class, BroadcastOnPostAtmosphereInterceptor.class, TrackMessageSizeInterceptor.class, HeartbeatInterceptor.class})
  • 85. 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); } }
  • 86. Client var 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'};
  • 87. Client request.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);
  • 89. Broadcaster • Default: in-memory • Cloud • RedisBroadcaster • JMSBroadcaster • XMPPBroadcaster • HazelcastBroadcaster • JGroupsBroascaster • Multi-Threads, Async I/O par default
  • 91.
  • 92. Atmosphere Components • WebSocketHandler • Only WebSocket (WARNING)! • AtmosphereHandler • All transports • Jersey Resource • All transports • Meteor • All transports
  • 93. Démo
  • 94. WebSocket Sub Protocol • WebSocketProtocol Define your own protocol on top of WebSocket • Default: WebSocket message => POST • SwaggerSocket:REST over WebSockets -> More information
  • 96. twitter.com/jfarcand twitter.com/atmo_framework twitter.com/swaggersocket http://github.com/Atmosphere/ http://github.com/wordnik/swaggersocket