Programming WebSockets with Glassfish and Grizzly

9,801 views

Published on

Slides of a tutorial at JavaOne 2012 about programming websockets with GlassFish and Grizzly

1 Comment
9 Likes
Statistics
Notes
No Downloads
Views
Total views
9,801
On SlideShare
0
From Embeds
0
Number of Embeds
2,816
Actions
Shares
0
Downloads
0
Comments
1
Likes
9
Embeds 0
No embeds

No notes for slide
  • What does it stand for – nothing (maybe Cloud2Business2Consulting)
  • 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.
  • 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
  • Lets look at Cache Usage Patterns
  • Used for ChatCould be used for new trades for a trader or bids or offers on a securityAsynchronous notificationManagement
  • Many other products have further features including filters etc.
  • Huge scalable GridHuge Parallel Processing CapabilityAsynchronous events -> via web socketsNot a database in sight!Add animations for executors + web sockets asynchronous events + needs clouding up
  • Programming WebSockets with Glassfish and Grizzly

    1. 1. Building Websocket ApplicationsWith Grizzly and Glassfish © C2B2 Consulting Limited 2012 All Rights Reserved
    2. 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. 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. 4. Standard HTTP modelClient requests data – server responds © C2B2 Consulting Limited 2012 All Rights Reserved
    5. 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. 6. Push to browser © C2B2 Consulting Limited 2012 All Rights Reserved
    7. 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. 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. 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. 10. Reverse AJAX/Comet• Utilises long polling or HTTP Streaming techniques• Complex development• Poor scalability © C2B2 Consulting Limited 2012 All Rights Reserved
    11. 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. 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. 13. Browser Support• Chrome 4+• Internet Explorer 10+• Firefox 4+• Opera 10.7+• Safari 5+ © C2B2 Consulting Limited 2012 All Rights Reserved
    14. 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. 15. Web Socket ProtocolClient ServerGET /chat HTTP/1.1 HTTP/1.1 101 SwitchingHost: server.example.com Protocols Upgrade: websocketUpgrade: websocket Connection: Upgrade Sec-Connection: Upgrade WebSocket-Accept:Sec-WebSocket-Key: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Protocol: chatOrigin: http://example.comSec-WebSocket-Protocol:chat, superchatSec-WebSocket-Version: 13 © C2B2 Consulting Limited 2012 All Rights Reserved
    16. 16. From the RFCConceptually, WebSocket is really just a layer on top ofTCP 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. 17. JavaScript APIWeb Socket Server Sent EventsWebSocket(location,protocol) EventSource(location)Function onmessage Function onmessageFunction onopen Function onopenFunction onclose Function onerrorFunction onerrorclose()send(data) © C2B2 Consulting Limited 2012 All Rights Reserved
    18. 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. 19. WebSockets in GlassFish © C2B2 Consulting Limited 2012 All Rights Reserved
    20. 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. 21. Enabling Web Socket support in Glassfishasadmin set configs.config.server-config.network-config.protocols.protocol.http-listener-1.http.websockets-support-enabled=truecan 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. 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. 23. Simple Echo © C2B2 Consulting Limited 2012 All Rights Reserved
    24. 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. 25. Echo ClassesEchoServlet WebSocket Engine EchoApplication © C2B2 Consulting Limited 2012 All Rights Reserved
    26. 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. 27. EchoApplicationpublic 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. 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. 29. Demo © C2B2 Consulting Limited 2012 All Rights Reserved
    30. 30. Extending with Push © C2B2 Consulting Limited 2012 All Rights Reserved
    31. 31. Push Demo Send String PushSocket Connects Createecho.jsp Response Request Creates EchoServlet EchoApplication © C2B2 Consulting Limited 2012 All Rights Reserved
    32. 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. 33. EchoApplicationpublic 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. 34. PushSocketpublic 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. 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. 36. Demo © C2B2 Consulting Limited 2012 All Rights Reserved
    37. 37. Data GridsReal Time Push at Scale? © C2B2 Consulting Limited 2012 All Rights Reserved
    38. 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. 39. HA Cache Partitioning B PUT BApplication Application Application Application Cache Cache Cache Cache NODE B CRASH !!! © C2B2 Consulting Limited 2012 All Rights Reserved
    40. 40. Typical Data GridApplication Application Application Application Application Application Application Cache Cache Cache Cache Cache Cache CacheApplication Application Application Application Application Application Application Cache Cache Cache Cache Cache Cache CacheApplication Application Application Application Application Application Application Cache Cache Cache Cache Cache Cache Cache © C2B2 Consulting Limited 2012 All Rights Reserved
    41. 41. Grid Events SubsystemApplication Application Application Application Cache Cache Cache Cache Listener Cache © C2B2 Consulting Limited 2012 All Rights Reserved
    42. 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. 43. JSR 107 APIboolean registerCacheEntryListener( CacheEntryListener cacheEntryListener);Fired on• Expired• Removed• Updated• Read © C2B2 Consulting Limited 2012 All Rights Reserved
    44. 44. Stock Ticker Architecture GlassFish Applicatio n CacheStockTicker App Applicatio n Cache © C2B2 Consulting Limited 2012 All Rights Reserved
    45. 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. 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. 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. 48. Stock Tickerpublic 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. 49. Stock Servletpublic 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. 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. 51. Stock Socketpublic 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. 52. stockticker.jspvar 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. 53. Demo © C2B2 Consulting Limited 2012 All Rights Reserved
    54. 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. 55. © C2B2 Consulting Limited 2012 All Rights Reserved

    ×