SlideShare uma empresa Scribd logo
1 de 55
Building Websocket
    Applications
With Grizzly and Glassfish




                     © C2B2 Consulting Limited 2012
                                All Rights Reserved
About Me
• Founder of C2B2
  – Leading Independent Middleware Experts
  – Non-functional Experts
• Vendor Neutral
  – Red Hat (JBoss), Oracle (Fusion), VMWare
    (vFabric), Open Source (Apache)
• 20 Years Middleware Expertise
• 15 years Field Consultancy
                              © C2B2 Consulting Limited 2012
                                         All Rights Reserved
Agenda

• Introduction to Web Sockets and Push
• WebSockets in GlassFish
• Code walkthrough - Basic Echo Server
• Code walkthrough - Pushing Stock prices to
  the browser
• Introduction to Data Grids
• Code walkthrough - Hooking up to a data grid
• Summary

                              © C2B2 Consulting Limited 2012
                                         All Rights Reserved
Standard HTTP model




Client requests data – server responds



                           © C2B2 Consulting Limited 2012
                                      All Rights Reserved
The problems with HTTP

•   HTTP is a request-response protocol
•   HTTP is half-duplex – one way traffic
•   HTTP is stateless – lots of redundant data
•   New connection required for each
    transaction



                                © C2B2 Consulting Limited 2012
                                           All Rights Reserved
Push to browser




             © C2B2 Consulting Limited 2012
                        All Rights Reserved
Simulated Push - Polling
• Regular requests at a set interval
• Near real-time
• Server events may occur between
  requests




                              © C2B2 Consulting Limited 2012
                                         All Rights Reserved
Simulated Push – Long polling
• Connection is kept open
• Response is blocked until an event occurs
  or a timeout occurs
• Resource hungry on the server




                             © C2B2 Consulting Limited 2012
                                        All Rights Reserved
HTTP Streaming
• Long lived HTTP connection
• Or XMLHttpRequest connection
• Browser needs to close and reconnect the
  streaming channel to release memory




                             © C2B2 Consulting Limited 2012
                                        All Rights Reserved
Reverse AJAX/Comet
• Utilises long polling or HTTP Streaming
  techniques
• Complex development
• Poor scalability




                              © C2B2 Consulting Limited 2012
                                         All Rights Reserved
The Future - Web Sockets
• New to HTML 5
• Enables Full Duplex communication
  between a browser and a Server
• Allows Web Servers to push updates to
  browsers
• Better than “long polling”
• Establishes a Dedicated Socket to the
  Backend Web Socket Server

                            © C2B2 Consulting Limited 2012
                                       All Rights Reserved
Web Socket standards

• This is all in flux
• Rfc 6455 defines the
  protocol
• W3C SSE
  http://dev.w3.org/html
  5/eventsource/
• W3C WebSockets
  http://dev.w3.org/html
  5/websockets/

                           © C2B2 Consulting Limited 2012
                                      All Rights Reserved
Browser Support
•   Chrome 4+
•   Internet Explorer 10+
•   Firefox 4+
•   Opera 10.7+
•   Safari 5+




                            © C2B2 Consulting Limited 2012
                                       All Rights Reserved
Benefits over old techniques
• Reduced latency
• Reduced network traffic
• Reduced CPU/memory usage on the
  server
• Scalable
• Simplified development



                          © C2B2 Consulting Limited 2012
                                     All Rights Reserved
Web Socket Protocol

Client                       Server

GET /chat HTTP/1.1           HTTP/1.1 101 Switching
Host: server.example.com     Protocols Upgrade: websocket
Upgrade: websocket           Connection: Upgrade Sec-
Connection: Upgrade          WebSocket-Accept:
Sec-WebSocket-Key:           s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
dGhlIHNhbXBsZSBub25jZQ==     Sec-WebSocket-Protocol: chat
Origin: http://example.com
Sec-WebSocket-Protocol:
chat, superchat
Sec-WebSocket-Version: 13



                                      © C2B2 Consulting Limited 2012
                                                 All Rights Reserved
From the RFC
Conceptually, WebSocket is really just a layer on top of
TCP that does the following:
• adds a web origin-based security model for browsers
• adds an addressing and protocol naming mechanism to
  support multiple services on one port and multiple host
  names on one IP address
• layers a framing mechanism on top of TCP to get back
  to the IP packet mechanism that TCP is built on, but
  without length limits
• includes an additional closing handshake in-band that is
  designed to work in the presence of proxies and other
  intermediaries
                                        © C2B2 Consulting Limited 2012
                                                   All Rights Reserved
JavaScript API

Web Socket                     Server Sent Events

WebSocket(location,protocol)   EventSource(location)

Function onmessage             Function onmessage
Function onopen                Function onopen
Function onclose               Function onerror
Function onerror
close()
send(data)



                                          © C2B2 Consulting Limited 2012
                                                     All Rights Reserved
W3C Definition
[Constructor(in DOMString url, in optional DOMString protocol)]
interface WebSocket {
  readonly attribute DOMString URL;

 // ready state
 const unsigned short CONNECTING = 0;
 const unsigned short OPEN = 1;
 const unsigned short CLOSED = 2;
 readonly attribute unsigned short readyState;
 readonly attribute unsigned long bufferedAmount;

  // networking
           attribute Function onopen;
           attribute Function onmessage;
           attribute Function onclose;
  boolean send(in DOMString data);
  void close();
};
WebSocket implements EventTarget;




                                                 © C2B2 Consulting Limited 2012
                                                            All Rights Reserved
WebSockets in GlassFish




                © C2B2 Consulting Limited 2012
                           All Rights Reserved
GlassFish
• Tutorial uses GlassFish 3.1.2
• Grizzly 1.9
• Not JEE6 Proposed API
  – GlassFish 4 build a little late for me
• Does Work NOW in Production builds




                                    © C2B2 Consulting Limited 2012
                                               All Rights Reserved
Enabling Web Socket support in Glassfish
asadmin set configs.config.server-config.network-
config.protocols.protocol.http-listener-
1.http.websockets-support-enabled=true



can be set via the admin console :
        -> server-config
         -> Network Config
           -> Network Listeners
            -> (select listener)
             -> HTTP tab
              -> Enable Websockets support



                                             © C2B2 Consulting Limited 2012
                                                        All Rights Reserved
Grizzly Key Classes
• Note this is 1.9.x shipped in GlassFish 3.2.x


                                             WebSocket

  WebSocket           WebSocket
   Engine             Application
                                             WebSocket



                                             WebSocket




                                    © C2B2 Consulting Limited 2012
                                               All Rights Reserved
Simple Echo




          © C2B2 Consulting Limited 2012
                     All Rights Reserved
Code Walkthrough
• Application – a very simple echo server
  that when sent a message echoes it back
• Developed using NetBeans with Glassfish
  Server 3.1.2 and Grizzly (comes with
  Glassfish)




                            © C2B2 Consulting Limited 2012
                                       All Rights Reserved
Echo Classes

EchoServlet



              WebSocket
               Engine


  Echo
Application




              © C2B2 Consulting Limited 2012
                         All Rights Reserved
EchoServlet
• Creates the application
      EchoApplication app = new EchoApplication();

• Overrides init and destroy methods
  Registers/unregisters the application

  WebSocketEngine.getEngine().register(app);

  WebSocketEngine.getEngine().unregister(app);




                                   © C2B2 Consulting Limited 2012
                                              All Rights Reserved
EchoApplication
public class EchoApplication extends WebSocketApplication {

public boolean isApplicationRequest(Request rqst) {
        if (rqst.requestURI().toString().endsWith("/echo")) {
            return true;
        } else {
            return false;
        }
    }

   @Override
   public void onMessage(WebSocket socket, String text) {
      socket.send(text);
   }




                                                   © C2B2 Consulting Limited 2012
                                                              All Rights Reserved
echo.jsp
• 3 buttons
    – Connect, Send, Disconnect
 var wsUri = "ws://" + location.host +
"${pageContext.request.contextPath}/echo";

function connect() {
    websocket = new WebSocket(wsUri);
    websocket.onmessage = function(event) { onMessage(event) };
}

function doSend(message) {
            websocket.send(message);
}

function onMessage(event) {
   writeToScreen('<span style="color: blue;">RESPONSE: ' +
event.data + '</span>');
}




                                                   © C2B2 Consulting Limited 2012
                                                              All Rights Reserved
Demo




       © C2B2 Consulting Limited 2012
                  All Rights Reserved
Extending with Push




               © C2B2 Consulting Limited 2012
                          All Rights Reserved
Push Demo


           Send String      PushSocket


                 Connects                     Create
echo.jsp
               Response


           Request                        Creates
                            EchoServlet                EchoApplication




                                                © C2B2 Consulting Limited 2012
                                                           All Rights Reserved
EchoServlet
• Creates the application
      EchoApplication app = new EchoApplication();

• Overrides init and destroy methods
  Registers/unregisters the application

  WebSocketEngine.getEngine().register(app);

  WebSocketEngine.getEngine().unregister(app);




                                   © C2B2 Consulting Limited 2012
                                              All Rights Reserved
EchoApplication
public class EchoApplication extends WebSocketApplication {

public boolean isApplicationRequest(Request rqst) {
        if (rqst.requestURI().toString().endsWith("/echo")) {
            return true;
        } else {
            return false;
        }
    }

 @Override
    public WebSocket createWebSocket(ProtocolHandler protocolHandler,
WebSocketListener... listeners) {
        return new PushSocket(protocolHandler,listeners);
    }




                                                   © C2B2 Consulting Limited 2012
                                                              All Rights Reserved
PushSocket
public class PushSocket extends DefaultWebSocket implements Runnable     {

public PushSocket(ProtocolHandler protocolHandler, WebSocketListener...
listeners ) {
        super(protocolHandler,listeners);
    }

public void onClose(DataFrame frame) {
        super.onClose(frame);
}
public void onConnect() {
        super.onConnect();
        Thread thread = new Thread(this);
        thread.run();
    }
public void run() {
   while (run && isConnected()) {
       this.send(Integer.toString(count++));
    }

                                                   © C2B2 Consulting Limited 2012
                                                              All Rights Reserved
echo.jsp
• 3 buttons
    – Connect, Send, Disconnect
 var wsUri = "ws://" + location.host +
"${pageContext.request.contextPath}/echo";

function connect() {
    websocket = new WebSocket(wsUri);
    websocket.onmessage = function(event) { onMessage(event) };
}

function onMessage(event) {
   writeToScreen('<span style="color: blue;">RESPONSE: ' +
event.data + '</span>');
}




                                                   © C2B2 Consulting Limited 2012
                                                              All Rights Reserved
Demo




       © C2B2 Consulting Limited 2012
                  All Rights Reserved
Data Grids


Real Time Push at Scale?




                   © C2B2 Consulting Limited 2012
                              All Rights Reserved
JCache
• JCache standard api for caches
• JSR 107 (Coming in JEE7)
• Provides Map Semantics for Cache
  – put(Key,Object)
  – Object get(Key)
• Most Caches support this api
• Coherence supports the api


                             © C2B2 Consulting Limited 2012
                                        All Rights Reserved
HA Cache Partitioning

         B
          PUT B


Application         Application   Application             Application



  Cache               Cache         Cache                    Cache
                                                             NODE
        B
                                                             CRASH
                                                               !!!




                                                © C2B2 Consulting Limited 2012
                                                           All Rights Reserved
Typical Data Grid

Application   Application    Application   Application   Application      Application     Application
  Cache         Cache          Cache         Cache         Cache            Cache           Cache




Application   Application    Application   Application   Application      Application     Application
  Cache         Cache          Cache         Cache         Cache            Cache           Cache




Application   Application    Application   Application   Application      Application     Application
  Cache         Cache          Cache         Cache         Cache            Cache           Cache




                                                                   © C2B2 Consulting Limited 2012
                                                                              All Rights Reserved
Grid Events Subsystem

Application       Application   Application             Application



     Cache          Cache         Cache                    Cache
    Listener



  Cache




                                              © C2B2 Consulting Limited 2012
                                                         All Rights Reserved
Coherence Event Listeners
• Coherence classes MapEvent,
  MapListener
• Each time a record is changed, Coherence
  raises a MapEvent
• Override entryUpdated, entryInserted and
  entryDeleted to process these events
• MapListeners can have filters


                            © C2B2 Consulting Limited 2012
                                       All Rights Reserved
JSR 107 API
boolean registerCacheEntryListener(
  CacheEntryListener cacheEntryListener);

Fired on
• Expired
• Removed
• Updated
• Read




                              © C2B2 Consulting Limited 2012
                                         All Rights Reserved
Stock Ticker Architecture


                  GlassFish

                       Applicatio
                       n Cache




StockTicker App

     Applicatio
     n Cache




                                    © C2B2 Consulting Limited 2012
                                               All Rights Reserved
Best Practice Architecture

                          Load Balancer

  JEE          JEE             JEE             JEE              JEE
  Cluster      Cluster         Cluster         Cluster          Cluster
  Node         Node            Node            Node             Node




  Applica   Applica      Applica     Applica    Applica   Applica         Applica
    Cac
  tion        Cac
            tion           Cac
                         tion          Cac
                                     tion         Cac
                                                tion        Cac
                                                          tion              Cac
                                                                          tion
   he        he           he             he       he       he              he


  Applica   Applica      Applica     Applica    Applica   Applica         Applica
    Cac
  tion        Cac
            tion           Cac
                         tion          Cac
                                     tion         Cac
                                                tion        Cac
                                                          tion              Cac
                                                                          tion
   he        he           he             he       he       he              he


  Applica   Applica      Applica     Applica    Applica   Applica         Applica
    Cac
  tion        Cac
            tion           Cac
                         tion          Cac
                                     tion         Cac
                                                tion        Cac
                                                          tion              Cac
                                                                          tion
   he        he           he             he       he       he              he




                                                          © C2B2 Consulting Limited 2012
                                                                     All Rights Reserved
Stock Ticker Classes
   Stock                               Stock
                 Stock
   Socket                              Ticker




   Stock        Named
 Application    Cache




  Stock        WebSocket
  Servlet       Engine



                         © C2B2 Consulting Limited 2012
                                    All Rights Reserved
Stock
    public class Stock implements Serializable {
      private   static   final long serialVersionUID = 1L;
      private   String   name;
      private   String   description;
      private   double   price;
}




                                          © C2B2 Consulting Limited 2012
                                                     All Rights Reserved
Stock Ticker
public static void main(String args[]) throws Exception {


      // attach to Coherence
      CacheFactory.ensureCluster();
      NamedCache cache = CacheFactory.getCache("SportingOdds");

      // create a random stock and stick it in Coherence
      while(true) {
          Stock stock = new Stock("C2B2","C2B2",Math.random() * 100.0);
          cache.put("C2B2", stock);

          myLogger.info("Stock Price " + stock.getPrice());
          int sleepTime = (int)(500*Math.random() + 500);
          Thread.currentThread().sleep(sleepTime);
      }
  }



                                                  © C2B2 Consulting Limited 2012
                                                             All Rights Reserved
Stock Servlet


public void init(ServletConfig config) throws ServletException
    {
        super.init(config);

       CacheFactory.ensureCluster();
       cohCache = CacheFactory.getCache("SportingOdds");
       pushApp = new StocksApplication(cohCache);
       WebSocketEngine.getEngine().register(pushApp);

   }




                                                   © C2B2 Consulting Limited 2012
                                                              All Rights Reserved
Stock Application

/**
      * Creates a web socket and starts up the <code>PusherRunnable</code>
thread.
      */
    public WebSocket createWebSocket(ProtocolHandler protocolHandler,
WebSocketListener... listeners)
    {
         logger.info("Stock Application - createWebSocket called");

          return new StockSocket(cohCache,protocolHandler, this, listeners);
      }




                                                     © C2B2 Consulting Limited 2012
                                                                All Rights Reserved
Stock Socket
public StockSocket(NamedCache cache, ProtocolHandler protocolHandler,
StocksApplication app, WebSocketListener... listeners) {
      myCache = cache;
    }
    public void onConnect() {
        myCache.addMapListener(this);
    }

   public void entryUpdated(MapEvent me) {
       if (me.getNewValue() instanceof Stock) {
           sendUpdate((Stock) me.getNewValue());
       }
   }

   public void sendUpdate(Stock stock) {
       ObjectMapper mapper = new ObjectMapper();
       StringWriter writer = new StringWriter();
       send(writer.toString());
   }
                                                   © C2B2 Consulting Limited 2012
                                                              All Rights Reserved
stockticker.jsp
var chart;
document.chart = new Highcharts.Chart({
                 ….
})




websocket.onmessage = function(event) {
   var object = JSON.parse(event.data);
   var x = (new Date()).getTime();
   var y = object.price;
    document.chart.series[0].addPoint([x,y],true,true,false);
  }




                                                   © C2B2 Consulting Limited 2012
                                                              All Rights Reserved
Demo




       © C2B2 Consulting Limited 2012
                  All Rights Reserved
Summary

• Reduced latency, network traffic and
  CPU/memory usage on the server
• Highly scalable
• When linked to a data grid, provide
  enterprise scale, event driven, real time
  push


                               © C2B2 Consulting Limited 2012
                                          All Rights Reserved
© C2B2 Consulting Limited 2012
           All Rights Reserved

Mais conteúdo relacionado

Mais procurados

WAS vs JBoss, WebLogic, Tomcat (year 2015)
WAS vs JBoss, WebLogic, Tomcat (year 2015)WAS vs JBoss, WebLogic, Tomcat (year 2015)
WAS vs JBoss, WebLogic, Tomcat (year 2015)Roman Kharkovski
 
JBoss EAP / WildFly, State of the Union
JBoss EAP / WildFly, State of the UnionJBoss EAP / WildFly, State of the Union
JBoss EAP / WildFly, State of the UnionDimitris Andreadis
 
WebSphere Technical University: Top WebSphere Problem Determination Features
WebSphere Technical University: Top WebSphere Problem Determination FeaturesWebSphere Technical University: Top WebSphere Problem Determination Features
WebSphere Technical University: Top WebSphere Problem Determination FeaturesChris Bailey
 
Weblogic configuration & administration
Weblogic   configuration & administrationWeblogic   configuration & administration
Weblogic configuration & administrationMuhammad Mansoor
 
JMS and ActiveMQ - VuNV 201307
JMS and ActiveMQ - VuNV 201307JMS and ActiveMQ - VuNV 201307
JMS and ActiveMQ - VuNV 201307Framgia Vietnam
 
WebSphere App Server vs JBoss vs WebLogic vs Tomcat
WebSphere App Server vs JBoss vs WebLogic vs TomcatWebSphere App Server vs JBoss vs WebLogic vs Tomcat
WebSphere App Server vs JBoss vs WebLogic vs TomcatWASdev Community
 
AAI-2075 Evolving an IBM WebSphere Topology to Manage a Changing Workloa
AAI-2075 Evolving an IBM WebSphere Topology to Manage a Changing WorkloaAAI-2075 Evolving an IBM WebSphere Topology to Manage a Changing Workloa
AAI-2075 Evolving an IBM WebSphere Topology to Manage a Changing WorkloaWASdev Community
 
Introducing WebLogic 12c OTN Tour 2012
Introducing WebLogic 12c OTN Tour 2012Introducing WebLogic 12c OTN Tour 2012
Introducing WebLogic 12c OTN Tour 2012Bruno Borges
 
Writing & Using Web Services
Writing & Using Web ServicesWriting & Using Web Services
Writing & Using Web ServicesRajarshi Guha
 
IBM WebSphere application server
IBM WebSphere application serverIBM WebSphere application server
IBM WebSphere application serverIBM Sverige
 
V cloud director 5.1 what's new overview technical presentation
V cloud director 5.1 what's new overview   technical presentationV cloud director 5.1 what's new overview   technical presentation
V cloud director 5.1 what's new overview technical presentationsolarisyourep
 
Cf summit2014 roadmap
Cf summit2014 roadmapCf summit2014 roadmap
Cf summit2014 roadmapJames Bayer
 
Using WebSphere MQ with WebSphere Application Server and the Liberty Profile
Using WebSphere MQ with WebSphere Application Server and the Liberty ProfileUsing WebSphere MQ with WebSphere Application Server and the Liberty Profile
Using WebSphere MQ with WebSphere Application Server and the Liberty Profilet_quigly
 
IBM MQ v8 and JMS 2.0
IBM MQ v8 and JMS 2.0IBM MQ v8 and JMS 2.0
IBM MQ v8 and JMS 2.0Matthew White
 
Maximize Messaging and Performance and Lowering Infrastructure Footprint
Maximize Messaging and Performance and Lowering Infrastructure FootprintMaximize Messaging and Performance and Lowering Infrastructure Footprint
Maximize Messaging and Performance and Lowering Infrastructure FootprintWSO2
 
Marketing Automation at Scale: How Marketo Solved Key Data Management Challen...
Marketing Automation at Scale: How Marketo Solved Key Data Management Challen...Marketing Automation at Scale: How Marketo Solved Key Data Management Challen...
Marketing Automation at Scale: How Marketo Solved Key Data Management Challen...Continuent
 

Mais procurados (20)

WAS vs JBoss, WebLogic, Tomcat (year 2015)
WAS vs JBoss, WebLogic, Tomcat (year 2015)WAS vs JBoss, WebLogic, Tomcat (year 2015)
WAS vs JBoss, WebLogic, Tomcat (year 2015)
 
JBoss EAP / WildFly, State of the Union
JBoss EAP / WildFly, State of the UnionJBoss EAP / WildFly, State of the Union
JBoss EAP / WildFly, State of the Union
 
WildFly & WildFly Swarm
WildFly & WildFly SwarmWildFly & WildFly Swarm
WildFly & WildFly Swarm
 
WebSphere Technical University: Top WebSphere Problem Determination Features
WebSphere Technical University: Top WebSphere Problem Determination FeaturesWebSphere Technical University: Top WebSphere Problem Determination Features
WebSphere Technical University: Top WebSphere Problem Determination Features
 
Weblogic configuration & administration
Weblogic   configuration & administrationWeblogic   configuration & administration
Weblogic configuration & administration
 
JMS and ActiveMQ - VuNV 201307
JMS and ActiveMQ - VuNV 201307JMS and ActiveMQ - VuNV 201307
JMS and ActiveMQ - VuNV 201307
 
WebSphere App Server vs JBoss vs WebLogic vs Tomcat
WebSphere App Server vs JBoss vs WebLogic vs TomcatWebSphere App Server vs JBoss vs WebLogic vs Tomcat
WebSphere App Server vs JBoss vs WebLogic vs Tomcat
 
IBM MQ vs Apache ActiveMQ
IBM MQ vs Apache ActiveMQIBM MQ vs Apache ActiveMQ
IBM MQ vs Apache ActiveMQ
 
IBM MQ V8 annd JMS 2.0
IBM MQ V8 annd JMS 2.0IBM MQ V8 annd JMS 2.0
IBM MQ V8 annd JMS 2.0
 
AAI-2075 Evolving an IBM WebSphere Topology to Manage a Changing Workloa
AAI-2075 Evolving an IBM WebSphere Topology to Manage a Changing WorkloaAAI-2075 Evolving an IBM WebSphere Topology to Manage a Changing Workloa
AAI-2075 Evolving an IBM WebSphere Topology to Manage a Changing Workloa
 
Introducing WebLogic 12c OTN Tour 2012
Introducing WebLogic 12c OTN Tour 2012Introducing WebLogic 12c OTN Tour 2012
Introducing WebLogic 12c OTN Tour 2012
 
Writing & Using Web Services
Writing & Using Web ServicesWriting & Using Web Services
Writing & Using Web Services
 
IBM WebSphere application server
IBM WebSphere application serverIBM WebSphere application server
IBM WebSphere application server
 
V cloud director 5.1 what's new overview technical presentation
V cloud director 5.1 what's new overview   technical presentationV cloud director 5.1 what's new overview   technical presentation
V cloud director 5.1 what's new overview technical presentation
 
Ronald van Luttikhuizen - Effective fault handling in SOA Suite and OSB 11g
Ronald van Luttikhuizen - Effective fault handling in SOA Suite and OSB 11gRonald van Luttikhuizen - Effective fault handling in SOA Suite and OSB 11g
Ronald van Luttikhuizen - Effective fault handling in SOA Suite and OSB 11g
 
Cf summit2014 roadmap
Cf summit2014 roadmapCf summit2014 roadmap
Cf summit2014 roadmap
 
Using WebSphere MQ with WebSphere Application Server and the Liberty Profile
Using WebSphere MQ with WebSphere Application Server and the Liberty ProfileUsing WebSphere MQ with WebSphere Application Server and the Liberty Profile
Using WebSphere MQ with WebSphere Application Server and the Liberty Profile
 
IBM MQ v8 and JMS 2.0
IBM MQ v8 and JMS 2.0IBM MQ v8 and JMS 2.0
IBM MQ v8 and JMS 2.0
 
Maximize Messaging and Performance and Lowering Infrastructure Footprint
Maximize Messaging and Performance and Lowering Infrastructure FootprintMaximize Messaging and Performance and Lowering Infrastructure Footprint
Maximize Messaging and Performance and Lowering Infrastructure Footprint
 
Marketing Automation at Scale: How Marketo Solved Key Data Management Challen...
Marketing Automation at Scale: How Marketo Solved Key Data Management Challen...Marketing Automation at Scale: How Marketo Solved Key Data Management Challen...
Marketing Automation at Scale: How Marketo Solved Key Data Management Challen...
 

Destaque

G1 Garbage Collector - Big Heaps and Low Pauses?
G1 Garbage Collector - Big Heaps and Low Pauses?G1 Garbage Collector - Big Heaps and Low Pauses?
G1 Garbage Collector - Big Heaps and Low Pauses?C2B2 Consulting
 
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/15streamdata.io
 
ITCamp 2012 - Florin Cardasim - HTML5 web-sockets
ITCamp 2012 - Florin Cardasim - HTML5 web-socketsITCamp 2012 - Florin Cardasim - HTML5 web-sockets
ITCamp 2012 - Florin Cardasim - HTML5 web-socketsITCamp
 
Building WebSocket and Server Side Events Applications using Atmosphere
Building WebSocket and Server Side Events Applications using AtmosphereBuilding WebSocket and Server Side Events Applications using Atmosphere
Building WebSocket and Server Side Events Applications using Atmospherejfarcand
 
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015Rich Cullen
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentationvlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets PresentationVolodymyr Lavrynovych
 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFishJava API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFishArun Gupta
 
Take Better Care of Library Data and Spreadsheets with Google Visualization A...
Take Better Care of Library Data and Spreadsheets with Google Visualization A...Take Better Care of Library Data and Spreadsheets with Google Visualization A...
Take Better Care of Library Data and Spreadsheets with Google Visualization A...Bohyun Kim
 

Destaque (8)

G1 Garbage Collector - Big Heaps and Low Pauses?
G1 Garbage Collector - Big Heaps and Low Pauses?G1 Garbage Collector - Big Heaps and Low Pauses?
G1 Garbage Collector - Big Heaps and Low Pauses?
 
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
 
ITCamp 2012 - Florin Cardasim - HTML5 web-sockets
ITCamp 2012 - Florin Cardasim - HTML5 web-socketsITCamp 2012 - Florin Cardasim - HTML5 web-sockets
ITCamp 2012 - Florin Cardasim - HTML5 web-sockets
 
Building WebSocket and Server Side Events Applications using Atmosphere
Building WebSocket and Server Side Events Applications using AtmosphereBuilding WebSocket and Server Side Events Applications using Atmosphere
Building WebSocket and Server Side Events Applications using Atmosphere
 
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentationvlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentation
 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFishJava API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFish
 
Take Better Care of Library Data and Spreadsheets with Google Visualization A...
Take Better Care of Library Data and Spreadsheets with Google Visualization A...Take Better Care of Library Data and Spreadsheets with Google Visualization A...
Take Better Care of Library Data and Spreadsheets with Google Visualization A...
 

Semelhante a Programming WebSockets with Glassfish and Grizzly

Oracle Coherence & WebLogic 12c Web Sockets: Delivering Real Time Push at Scale
Oracle Coherence & WebLogic 12c Web Sockets: Delivering Real Time Push at ScaleOracle Coherence & WebLogic 12c Web Sockets: Delivering Real Time Push at Scale
Oracle Coherence & WebLogic 12c Web Sockets: Delivering Real Time Push at ScaleC2B2 Consulting
 
HTML5 WebSocket Introduction
HTML5 WebSocket IntroductionHTML5 WebSocket Introduction
HTML5 WebSocket IntroductionMarcelo Jabali
 
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/CamelCamelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/CamelCharles Moulliard
 
Monitoring VMware vFabric with Hyperic and Spring Insight
Monitoring VMware vFabric with Hyperic and Spring InsightMonitoring VMware vFabric with Hyperic and Spring Insight
Monitoring VMware vFabric with Hyperic and Spring InsightC2B2 Consulting
 
SPDY - http reloaded - WebTechConference 2012
SPDY - http reloaded - WebTechConference 2012SPDY - http reloaded - WebTechConference 2012
SPDY - http reloaded - WebTechConference 2012Fabian Lange
 
Jetty 9 – The Next Generation Servlet Container
Jetty 9 – The Next Generation Servlet ContainerJetty 9 – The Next Generation Servlet Container
Jetty 9 – The Next Generation Servlet ContainerCodemotion
 
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)Peter Lubbers
 
DDS on the Web: Quick Recipes for Real-Time Web Applications
DDS on the Web: Quick Recipes for Real-Time Web ApplicationsDDS on the Web: Quick Recipes for Real-Time Web Applications
DDS on the Web: Quick Recipes for Real-Time Web ApplicationsAngelo Corsaro
 
Desayuno Tecnico OVN - Xsigo
Desayuno Tecnico OVN - XsigoDesayuno Tecnico OVN - Xsigo
Desayuno Tecnico OVN - XsigoFran Navarro
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaHTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaJAX London
 
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012Arun Gupta
 
JBoss AS7 by Matt Brasier
JBoss AS7 by Matt BrasierJBoss AS7 by Matt Brasier
JBoss AS7 by Matt BrasierJBUG London
 
Cisco Cloupia uic product overview and demo presentation
Cisco Cloupia uic product overview and demo presentationCisco Cloupia uic product overview and demo presentation
Cisco Cloupia uic product overview and demo presentationxKinAnx
 
HTML5 Real-Time and Connectivity
HTML5 Real-Time and ConnectivityHTML5 Real-Time and Connectivity
HTML5 Real-Time and ConnectivityPeter Lubbers
 
Custom Runtimes for the Cloud
Custom Runtimes for the CloudCustom Runtimes for the Cloud
Custom Runtimes for the CloudCloudBees
 
Software Defined Networking/Openflow: A path to Programmable Networks
Software Defined Networking/Openflow: A path to Programmable NetworksSoftware Defined Networking/Openflow: A path to Programmable Networks
Software Defined Networking/Openflow: A path to Programmable NetworksMyNOG
 
HiveServer2 for Apache Hive
HiveServer2 for Apache HiveHiveServer2 for Apache Hive
HiveServer2 for Apache HiveCarl Steinbach
 
Ignite 2017 - Windows Server Feature Release
Ignite 2017 - Windows Server Feature ReleaseIgnite 2017 - Windows Server Feature Release
Ignite 2017 - Windows Server Feature ReleaseTaylor Brown
 

Semelhante a Programming WebSockets with Glassfish and Grizzly (20)

Oracle Coherence & WebLogic 12c Web Sockets: Delivering Real Time Push at Scale
Oracle Coherence & WebLogic 12c Web Sockets: Delivering Real Time Push at ScaleOracle Coherence & WebLogic 12c Web Sockets: Delivering Real Time Push at Scale
Oracle Coherence & WebLogic 12c Web Sockets: Delivering Real Time Push at Scale
 
HTML5 WebSocket Introduction
HTML5 WebSocket IntroductionHTML5 WebSocket Introduction
HTML5 WebSocket Introduction
 
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/CamelCamelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
 
Monitoring VMware vFabric with Hyperic and Spring Insight
Monitoring VMware vFabric with Hyperic and Spring InsightMonitoring VMware vFabric with Hyperic and Spring Insight
Monitoring VMware vFabric with Hyperic and Spring Insight
 
SPDY - http reloaded - WebTechConference 2012
SPDY - http reloaded - WebTechConference 2012SPDY - http reloaded - WebTechConference 2012
SPDY - http reloaded - WebTechConference 2012
 
Jetty 9 – The Next Generation Servlet Container
Jetty 9 – The Next Generation Servlet ContainerJetty 9 – The Next Generation Servlet Container
Jetty 9 – The Next Generation Servlet Container
 
Websocket 1.0
Websocket 1.0Websocket 1.0
Websocket 1.0
 
Real Time With Web Sockets
Real Time With Web SocketsReal Time With Web Sockets
Real Time With Web Sockets
 
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
 
DDS on the Web: Quick Recipes for Real-Time Web Applications
DDS on the Web: Quick Recipes for Real-Time Web ApplicationsDDS on the Web: Quick Recipes for Real-Time Web Applications
DDS on the Web: Quick Recipes for Real-Time Web Applications
 
Desayuno Tecnico OVN - Xsigo
Desayuno Tecnico OVN - XsigoDesayuno Tecnico OVN - Xsigo
Desayuno Tecnico OVN - Xsigo
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaHTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun Gupta
 
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
 
JBoss AS7 by Matt Brasier
JBoss AS7 by Matt BrasierJBoss AS7 by Matt Brasier
JBoss AS7 by Matt Brasier
 
Cisco Cloupia uic product overview and demo presentation
Cisco Cloupia uic product overview and demo presentationCisco Cloupia uic product overview and demo presentation
Cisco Cloupia uic product overview and demo presentation
 
HTML5 Real-Time and Connectivity
HTML5 Real-Time and ConnectivityHTML5 Real-Time and Connectivity
HTML5 Real-Time and Connectivity
 
Custom Runtimes for the Cloud
Custom Runtimes for the CloudCustom Runtimes for the Cloud
Custom Runtimes for the Cloud
 
Software Defined Networking/Openflow: A path to Programmable Networks
Software Defined Networking/Openflow: A path to Programmable NetworksSoftware Defined Networking/Openflow: A path to Programmable Networks
Software Defined Networking/Openflow: A path to Programmable Networks
 
HiveServer2 for Apache Hive
HiveServer2 for Apache HiveHiveServer2 for Apache Hive
HiveServer2 for Apache Hive
 
Ignite 2017 - Windows Server Feature Release
Ignite 2017 - Windows Server Feature ReleaseIgnite 2017 - Windows Server Feature Release
Ignite 2017 - Windows Server Feature Release
 

Mais de C2B2 Consulting

Monitoring Oracle SOA Suite - UKOUG Tech15 2015
Monitoring Oracle SOA Suite - UKOUG Tech15 2015Monitoring Oracle SOA Suite - UKOUG Tech15 2015
Monitoring Oracle SOA Suite - UKOUG Tech15 2015C2B2 Consulting
 
Hands-on Performance Tuning Lab - Devoxx Poland
Hands-on Performance Tuning Lab - Devoxx PolandHands-on Performance Tuning Lab - Devoxx Poland
Hands-on Performance Tuning Lab - Devoxx PolandC2B2 Consulting
 
Monitoring Oracle SOA Suite
Monitoring Oracle SOA SuiteMonitoring Oracle SOA Suite
Monitoring Oracle SOA SuiteC2B2 Consulting
 
Advanced queries on the Infinispan Data Grid
Advanced queries on the Infinispan Data Grid Advanced queries on the Infinispan Data Grid
Advanced queries on the Infinispan Data Grid C2B2 Consulting
 
Hands-on Performance Workshop - The science of performance
Hands-on Performance Workshop - The science of performanceHands-on Performance Workshop - The science of performance
Hands-on Performance Workshop - The science of performanceC2B2 Consulting
 
Jsr107 come, code, cache, compute!
Jsr107 come, code, cache, compute!Jsr107 come, code, cache, compute!
Jsr107 come, code, cache, compute!C2B2 Consulting
 
JBoss Clustering on OpenShift
JBoss Clustering on OpenShiftJBoss Clustering on OpenShift
JBoss Clustering on OpenShiftC2B2 Consulting
 
Dr. Low Latency or: How I Learned to Stop Worrying about Pauses and Love the ...
Dr. Low Latency or: How I Learned to Stop Worrying about Pauses and Love the ...Dr. Low Latency or: How I Learned to Stop Worrying about Pauses and Love the ...
Dr. Low Latency or: How I Learned to Stop Worrying about Pauses and Love the ...C2B2 Consulting
 
Java Middleware Surgery
Java Middleware Surgery Java Middleware Surgery
Java Middleware Surgery C2B2 Consulting
 
Oracle SOA Suite Performance Tuning- UKOUG Application Server & Middleware SI...
Oracle SOA Suite Performance Tuning- UKOUG Application Server & Middleware SI...Oracle SOA Suite Performance Tuning- UKOUG Application Server & Middleware SI...
Oracle SOA Suite Performance Tuning- UKOUG Application Server & Middleware SI...C2B2 Consulting
 
'Deploying with GlassFish & Docker'
'Deploying with GlassFish & Docker' 'Deploying with GlassFish & Docker'
'Deploying with GlassFish & Docker' C2B2 Consulting
 
'JMS @ Data Grid? Hacking the Glassfish messaging for fun & profit'
'JMS @ Data Grid? Hacking the Glassfish messaging for fun & profit' 'JMS @ Data Grid? Hacking the Glassfish messaging for fun & profit'
'JMS @ Data Grid? Hacking the Glassfish messaging for fun & profit' C2B2 Consulting
 
'New JMS features in GlassFish 4.0' by Nigel Deakin
'New JMS features in GlassFish 4.0' by Nigel Deakin'New JMS features in GlassFish 4.0' by Nigel Deakin
'New JMS features in GlassFish 4.0' by Nigel DeakinC2B2 Consulting
 
Coherence sig-nfr-web-tier-scaling-using-coherence-web
Coherence sig-nfr-web-tier-scaling-using-coherence-webCoherence sig-nfr-web-tier-scaling-using-coherence-web
Coherence sig-nfr-web-tier-scaling-using-coherence-webC2B2 Consulting
 
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 ScaleC2B2 Consulting
 
GeeCon- 'www.NoSQL.com' by Mark Addy
GeeCon- 'www.NoSQL.com' by Mark Addy GeeCon- 'www.NoSQL.com' by Mark Addy
GeeCon- 'www.NoSQL.com' by Mark Addy C2B2 Consulting
 
Middleware Expert Support Presentation
Middleware Expert Support PresentationMiddleware Expert Support Presentation
Middleware Expert Support PresentationC2B2 Consulting
 
Monitoring Production JBoss with JBoss ON
Monitoring Production JBoss with JBoss ONMonitoring Production JBoss with JBoss ON
Monitoring Production JBoss with JBoss ONC2B2 Consulting
 

Mais de C2B2 Consulting (20)

Monitoring Oracle SOA Suite - UKOUG Tech15 2015
Monitoring Oracle SOA Suite - UKOUG Tech15 2015Monitoring Oracle SOA Suite - UKOUG Tech15 2015
Monitoring Oracle SOA Suite - UKOUG Tech15 2015
 
Hands-on Performance Tuning Lab - Devoxx Poland
Hands-on Performance Tuning Lab - Devoxx PolandHands-on Performance Tuning Lab - Devoxx Poland
Hands-on Performance Tuning Lab - Devoxx Poland
 
Monitoring Oracle SOA Suite
Monitoring Oracle SOA SuiteMonitoring Oracle SOA Suite
Monitoring Oracle SOA Suite
 
Advanced queries on the Infinispan Data Grid
Advanced queries on the Infinispan Data Grid Advanced queries on the Infinispan Data Grid
Advanced queries on the Infinispan Data Grid
 
Through the JMX Window
Through the JMX WindowThrough the JMX Window
Through the JMX Window
 
Hands-on Performance Workshop - The science of performance
Hands-on Performance Workshop - The science of performanceHands-on Performance Workshop - The science of performance
Hands-on Performance Workshop - The science of performance
 
Jsr107 come, code, cache, compute!
Jsr107 come, code, cache, compute!Jsr107 come, code, cache, compute!
Jsr107 come, code, cache, compute!
 
JBoss Clustering on OpenShift
JBoss Clustering on OpenShiftJBoss Clustering on OpenShift
JBoss Clustering on OpenShift
 
Dr. Low Latency or: How I Learned to Stop Worrying about Pauses and Love the ...
Dr. Low Latency or: How I Learned to Stop Worrying about Pauses and Love the ...Dr. Low Latency or: How I Learned to Stop Worrying about Pauses and Love the ...
Dr. Low Latency or: How I Learned to Stop Worrying about Pauses and Love the ...
 
Java Middleware Surgery
Java Middleware Surgery Java Middleware Surgery
Java Middleware Surgery
 
Jax London 2013
Jax London 2013Jax London 2013
Jax London 2013
 
Oracle SOA Suite Performance Tuning- UKOUG Application Server & Middleware SI...
Oracle SOA Suite Performance Tuning- UKOUG Application Server & Middleware SI...Oracle SOA Suite Performance Tuning- UKOUG Application Server & Middleware SI...
Oracle SOA Suite Performance Tuning- UKOUG Application Server & Middleware SI...
 
'Deploying with GlassFish & Docker'
'Deploying with GlassFish & Docker' 'Deploying with GlassFish & Docker'
'Deploying with GlassFish & Docker'
 
'JMS @ Data Grid? Hacking the Glassfish messaging for fun & profit'
'JMS @ Data Grid? Hacking the Glassfish messaging for fun & profit' 'JMS @ Data Grid? Hacking the Glassfish messaging for fun & profit'
'JMS @ Data Grid? Hacking the Glassfish messaging for fun & profit'
 
'New JMS features in GlassFish 4.0' by Nigel Deakin
'New JMS features in GlassFish 4.0' by Nigel Deakin'New JMS features in GlassFish 4.0' by Nigel Deakin
'New JMS features in GlassFish 4.0' by Nigel Deakin
 
Coherence sig-nfr-web-tier-scaling-using-coherence-web
Coherence sig-nfr-web-tier-scaling-using-coherence-webCoherence sig-nfr-web-tier-scaling-using-coherence-web
Coherence sig-nfr-web-tier-scaling-using-coherence-web
 
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
 
GeeCon- 'www.NoSQL.com' by Mark Addy
GeeCon- 'www.NoSQL.com' by Mark Addy GeeCon- 'www.NoSQL.com' by Mark Addy
GeeCon- 'www.NoSQL.com' by Mark Addy
 
Middleware Expert Support Presentation
Middleware Expert Support PresentationMiddleware Expert Support Presentation
Middleware Expert Support Presentation
 
Monitoring Production JBoss with JBoss ON
Monitoring Production JBoss with JBoss ONMonitoring Production JBoss with JBoss ON
Monitoring Production JBoss with JBoss ON
 

Programming WebSockets with Glassfish and Grizzly

  • 1. Building Websocket Applications With Grizzly and Glassfish © C2B2 Consulting Limited 2012 All Rights Reserved
  • 2. About Me • Founder of C2B2 – Leading Independent Middleware Experts – Non-functional Experts • Vendor Neutral – Red Hat (JBoss), Oracle (Fusion), VMWare (vFabric), Open Source (Apache) • 20 Years Middleware Expertise • 15 years Field Consultancy © C2B2 Consulting Limited 2012 All Rights Reserved
  • 3. Agenda • Introduction to Web Sockets and Push • WebSockets in GlassFish • Code walkthrough - Basic Echo Server • Code walkthrough - Pushing Stock prices to the browser • Introduction to Data Grids • Code walkthrough - Hooking up to a data grid • Summary © C2B2 Consulting Limited 2012 All Rights Reserved
  • 4. Standard HTTP model Client requests data – server responds © C2B2 Consulting Limited 2012 All Rights Reserved
  • 5. The problems with HTTP • HTTP is a request-response protocol • HTTP is half-duplex – one way traffic • HTTP is stateless – lots of redundant data • New connection required for each transaction © C2B2 Consulting Limited 2012 All Rights Reserved
  • 6. Push to browser © C2B2 Consulting Limited 2012 All Rights Reserved
  • 7. Simulated Push - Polling • Regular requests at a set interval • Near real-time • Server events may occur between requests © C2B2 Consulting Limited 2012 All Rights Reserved
  • 8. Simulated Push – Long polling • Connection is kept open • Response is blocked until an event occurs or a timeout occurs • Resource hungry on the server © C2B2 Consulting Limited 2012 All Rights Reserved
  • 9. HTTP Streaming • Long lived HTTP connection • Or XMLHttpRequest connection • Browser needs to close and reconnect the streaming channel to release memory © C2B2 Consulting Limited 2012 All Rights Reserved
  • 10. Reverse AJAX/Comet • Utilises long polling or HTTP Streaming techniques • Complex development • Poor scalability © C2B2 Consulting Limited 2012 All Rights Reserved
  • 11. The Future - Web Sockets • New to HTML 5 • Enables Full Duplex communication between a browser and a Server • Allows Web Servers to push updates to browsers • Better than “long polling” • Establishes a Dedicated Socket to the Backend Web Socket Server © C2B2 Consulting Limited 2012 All Rights Reserved
  • 12. Web Socket standards • This is all in flux • Rfc 6455 defines the protocol • W3C SSE http://dev.w3.org/html 5/eventsource/ • W3C WebSockets http://dev.w3.org/html 5/websockets/ © C2B2 Consulting Limited 2012 All Rights Reserved
  • 13. Browser Support • Chrome 4+ • Internet Explorer 10+ • Firefox 4+ • Opera 10.7+ • Safari 5+ © C2B2 Consulting Limited 2012 All Rights Reserved
  • 14. Benefits over old techniques • Reduced latency • Reduced network traffic • Reduced CPU/memory usage on the server • Scalable • Simplified development © C2B2 Consulting Limited 2012 All Rights Reserved
  • 15. Web Socket Protocol Client Server GET /chat HTTP/1.1 HTTP/1.1 101 Switching Host: server.example.com Protocols Upgrade: websocket Upgrade: websocket Connection: Upgrade Sec- Connection: Upgrade WebSocket-Accept: Sec-WebSocket-Key: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Protocol: chat Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 © C2B2 Consulting Limited 2012 All Rights Reserved
  • 16. From the RFC Conceptually, WebSocket is really just a layer on top of TCP that does the following: • adds a web origin-based security model for browsers • adds an addressing and protocol naming mechanism to support multiple services on one port and multiple host names on one IP address • layers a framing mechanism on top of TCP to get back to the IP packet mechanism that TCP is built on, but without length limits • includes an additional closing handshake in-band that is designed to work in the presence of proxies and other intermediaries © C2B2 Consulting Limited 2012 All Rights Reserved
  • 17. JavaScript API Web Socket Server Sent Events WebSocket(location,protocol) EventSource(location) Function onmessage Function onmessage Function onopen Function onopen Function onclose Function onerror Function onerror close() send(data) © C2B2 Consulting Limited 2012 All Rights Reserved
  • 18. W3C Definition [Constructor(in DOMString url, in optional DOMString protocol)] interface WebSocket { readonly attribute DOMString URL; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSED = 2; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount; // networking attribute Function onopen; attribute Function onmessage; attribute Function onclose; boolean send(in DOMString data); void close(); }; WebSocket implements EventTarget; © C2B2 Consulting Limited 2012 All Rights Reserved
  • 19. WebSockets in GlassFish © C2B2 Consulting Limited 2012 All Rights Reserved
  • 20. GlassFish • Tutorial uses GlassFish 3.1.2 • Grizzly 1.9 • Not JEE6 Proposed API – GlassFish 4 build a little late for me • Does Work NOW in Production builds © C2B2 Consulting Limited 2012 All Rights Reserved
  • 21. Enabling Web Socket support in Glassfish asadmin set configs.config.server-config.network- config.protocols.protocol.http-listener- 1.http.websockets-support-enabled=true can be set via the admin console : -> server-config -> Network Config -> Network Listeners -> (select listener) -> HTTP tab -> Enable Websockets support © C2B2 Consulting Limited 2012 All Rights Reserved
  • 22. Grizzly Key Classes • Note this is 1.9.x shipped in GlassFish 3.2.x WebSocket WebSocket WebSocket Engine Application WebSocket WebSocket © C2B2 Consulting Limited 2012 All Rights Reserved
  • 23. Simple Echo © C2B2 Consulting Limited 2012 All Rights Reserved
  • 24. Code Walkthrough • Application – a very simple echo server that when sent a message echoes it back • Developed using NetBeans with Glassfish Server 3.1.2 and Grizzly (comes with Glassfish) © C2B2 Consulting Limited 2012 All Rights Reserved
  • 25. Echo Classes EchoServlet WebSocket Engine Echo Application © C2B2 Consulting Limited 2012 All Rights Reserved
  • 26. EchoServlet • Creates the application EchoApplication app = new EchoApplication(); • Overrides init and destroy methods Registers/unregisters the application WebSocketEngine.getEngine().register(app); WebSocketEngine.getEngine().unregister(app); © C2B2 Consulting Limited 2012 All Rights Reserved
  • 27. EchoApplication public class EchoApplication extends WebSocketApplication { public boolean isApplicationRequest(Request rqst) { if (rqst.requestURI().toString().endsWith("/echo")) { return true; } else { return false; } } @Override public void onMessage(WebSocket socket, String text) { socket.send(text); } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 28. echo.jsp • 3 buttons – Connect, Send, Disconnect var wsUri = "ws://" + location.host + "${pageContext.request.contextPath}/echo"; function connect() { websocket = new WebSocket(wsUri); websocket.onmessage = function(event) { onMessage(event) }; } function doSend(message) { websocket.send(message); } function onMessage(event) { writeToScreen('<span style="color: blue;">RESPONSE: ' + event.data + '</span>'); } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 29. Demo © C2B2 Consulting Limited 2012 All Rights Reserved
  • 30. Extending with Push © C2B2 Consulting Limited 2012 All Rights Reserved
  • 31. Push Demo Send String PushSocket Connects Create echo.jsp Response Request Creates EchoServlet EchoApplication © C2B2 Consulting Limited 2012 All Rights Reserved
  • 32. EchoServlet • Creates the application EchoApplication app = new EchoApplication(); • Overrides init and destroy methods Registers/unregisters the application WebSocketEngine.getEngine().register(app); WebSocketEngine.getEngine().unregister(app); © C2B2 Consulting Limited 2012 All Rights Reserved
  • 33. EchoApplication public class EchoApplication extends WebSocketApplication { public boolean isApplicationRequest(Request rqst) { if (rqst.requestURI().toString().endsWith("/echo")) { return true; } else { return false; } } @Override public WebSocket createWebSocket(ProtocolHandler protocolHandler, WebSocketListener... listeners) { return new PushSocket(protocolHandler,listeners); } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 34. PushSocket public class PushSocket extends DefaultWebSocket implements Runnable { public PushSocket(ProtocolHandler protocolHandler, WebSocketListener... listeners ) { super(protocolHandler,listeners); } public void onClose(DataFrame frame) { super.onClose(frame); } public void onConnect() { super.onConnect(); Thread thread = new Thread(this); thread.run(); } public void run() { while (run && isConnected()) { this.send(Integer.toString(count++)); } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 35. echo.jsp • 3 buttons – Connect, Send, Disconnect var wsUri = "ws://" + location.host + "${pageContext.request.contextPath}/echo"; function connect() { websocket = new WebSocket(wsUri); websocket.onmessage = function(event) { onMessage(event) }; } function onMessage(event) { writeToScreen('<span style="color: blue;">RESPONSE: ' + event.data + '</span>'); } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 36. Demo © C2B2 Consulting Limited 2012 All Rights Reserved
  • 37. Data Grids Real Time Push at Scale? © C2B2 Consulting Limited 2012 All Rights Reserved
  • 38. JCache • JCache standard api for caches • JSR 107 (Coming in JEE7) • Provides Map Semantics for Cache – put(Key,Object) – Object get(Key) • Most Caches support this api • Coherence supports the api © C2B2 Consulting Limited 2012 All Rights Reserved
  • 39. HA Cache Partitioning B PUT B Application Application Application Application Cache Cache Cache Cache NODE B CRASH !!! © C2B2 Consulting Limited 2012 All Rights Reserved
  • 40. Typical Data Grid Application Application Application Application Application Application Application Cache Cache Cache Cache Cache Cache Cache Application Application Application Application Application Application Application Cache Cache Cache Cache Cache Cache Cache Application Application Application Application Application Application Application Cache Cache Cache Cache Cache Cache Cache © C2B2 Consulting Limited 2012 All Rights Reserved
  • 41. Grid Events Subsystem Application Application Application Application Cache Cache Cache Cache Listener Cache © C2B2 Consulting Limited 2012 All Rights Reserved
  • 42. Coherence Event Listeners • Coherence classes MapEvent, MapListener • Each time a record is changed, Coherence raises a MapEvent • Override entryUpdated, entryInserted and entryDeleted to process these events • MapListeners can have filters © C2B2 Consulting Limited 2012 All Rights Reserved
  • 43. JSR 107 API boolean registerCacheEntryListener( CacheEntryListener cacheEntryListener); Fired on • Expired • Removed • Updated • Read © C2B2 Consulting Limited 2012 All Rights Reserved
  • 44. Stock Ticker Architecture GlassFish Applicatio n Cache StockTicker App Applicatio n Cache © C2B2 Consulting Limited 2012 All Rights Reserved
  • 45. Best Practice Architecture Load Balancer JEE JEE JEE JEE JEE Cluster Cluster Cluster Cluster Cluster Node Node Node Node Node Applica Applica Applica Applica Applica Applica Applica Cac tion Cac tion Cac tion Cac tion Cac tion Cac tion Cac tion he he he he he he he Applica Applica Applica Applica Applica Applica Applica Cac tion Cac tion Cac tion Cac tion Cac tion Cac tion Cac tion he he he he he he he Applica Applica Applica Applica Applica Applica Applica Cac tion Cac tion Cac tion Cac tion Cac tion Cac tion Cac tion he he he he he he he © C2B2 Consulting Limited 2012 All Rights Reserved
  • 46. Stock Ticker Classes Stock Stock Stock Socket Ticker Stock Named Application Cache Stock WebSocket Servlet Engine © C2B2 Consulting Limited 2012 All Rights Reserved
  • 47. Stock public class Stock implements Serializable { private static final long serialVersionUID = 1L; private String name; private String description; private double price; } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 48. Stock Ticker public static void main(String args[]) throws Exception { // attach to Coherence CacheFactory.ensureCluster(); NamedCache cache = CacheFactory.getCache("SportingOdds"); // create a random stock and stick it in Coherence while(true) { Stock stock = new Stock("C2B2","C2B2",Math.random() * 100.0); cache.put("C2B2", stock); myLogger.info("Stock Price " + stock.getPrice()); int sleepTime = (int)(500*Math.random() + 500); Thread.currentThread().sleep(sleepTime); } } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 49. Stock Servlet public void init(ServletConfig config) throws ServletException { super.init(config); CacheFactory.ensureCluster(); cohCache = CacheFactory.getCache("SportingOdds"); pushApp = new StocksApplication(cohCache); WebSocketEngine.getEngine().register(pushApp); } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 50. Stock Application /** * Creates a web socket and starts up the <code>PusherRunnable</code> thread. */ public WebSocket createWebSocket(ProtocolHandler protocolHandler, WebSocketListener... listeners) { logger.info("Stock Application - createWebSocket called"); return new StockSocket(cohCache,protocolHandler, this, listeners); } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 51. Stock Socket public StockSocket(NamedCache cache, ProtocolHandler protocolHandler, StocksApplication app, WebSocketListener... listeners) { myCache = cache; } public void onConnect() { myCache.addMapListener(this); } public void entryUpdated(MapEvent me) { if (me.getNewValue() instanceof Stock) { sendUpdate((Stock) me.getNewValue()); } } public void sendUpdate(Stock stock) { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); send(writer.toString()); } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 52. stockticker.jsp var chart; document.chart = new Highcharts.Chart({ …. }) websocket.onmessage = function(event) { var object = JSON.parse(event.data); var x = (new Date()).getTime(); var y = object.price; document.chart.series[0].addPoint([x,y],true,true,false); } © C2B2 Consulting Limited 2012 All Rights Reserved
  • 53. Demo © C2B2 Consulting Limited 2012 All Rights Reserved
  • 54. Summary • Reduced latency, network traffic and CPU/memory usage on the server • Highly scalable • When linked to a data grid, provide enterprise scale, event driven, real time push © C2B2 Consulting Limited 2012 All Rights Reserved
  • 55. © C2B2 Consulting Limited 2012 All Rights Reserved

Notas do Editor

  1. What does it stand for – nothing (maybe Cloud2Business2Consulting)
  2. Bytes overhead is large on long polling can be up to a K for request and responseHalf duplex so need to maintain 2 sockets one receiving responses one sending requests then correlating requests to responses.
  3. Protocol tells the server which protocols it can talkServer chooses oneKey exchange is to ensure genuine websocket clients are talking to the server.Server must respond with a 101 switching response and the correct key in the accept.SEC headers cannot be set by an attacker using Javascript and HTML
  4. Lets look at Cache Usage Patterns
  5. Used for ChatCould be used for new trades for a trader or bids or offers on a securityAsynchronous notificationManagement
  6. Many other products have further features including filters etc.
  7. Huge scalable GridHuge Parallel Processing CapabilityAsynchronous events -&gt; via web socketsNot a database in sight!Add animations for executors + web sockets asynchronous events + needs clouding up