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

Programming WebSockets with Glassfish and Grizzly

  • 1.
    Building Websocket Applications With Grizzly and Glassfish © C2B2 Consulting Limited 2012 All Rights Reserved
  • 2.
    About Me • Founderof 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 toWeb 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 Clientrequests data – server responds © C2B2 Consulting Limited 2012 All Rights Reserved
  • 5.
    The problems withHTTP • 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 • Longlived 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 • Utiliseslong 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 oldtechniques • 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 DOMStringurl, 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 usesGlassFish 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 Socketsupport 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 theapplication 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 EchoApplicationextends 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 theapplication 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 EchoApplicationextends 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 PushSocketextends 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 TimePush at Scale? © C2B2 Consulting Limited 2012 All Rights Reserved
  • 38.
    JCache • JCache standardapi 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 booleanregisterCacheEntryListener( 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 staticvoid 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 voidinit(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(NamedCachecache, 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 ConsultingLimited 2012 All Rights Reserved

Editor's Notes

  • #3 What does it stand for – nothing (maybe Cloud2Business2Consulting)
  • #12 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.
  • #16 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
  • #39 Lets look at Cache Usage Patterns
  • #42 Used for ChatCould be used for new trades for a trader or bids or offers on a securityAsynchronous notificationManagement
  • #44 Many other products have further features including filters etc.
  • #46 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