Speed up your Web applications with HTML5 WebSockets

2,540 views
2,436 views

Published on

This presentation compares the network communications done with HTTP request/Response, Server-Sent Events and WebSockets.

Published in: Technology, Education
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,540
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide

Speed up your Web applications with HTML5 WebSockets

  1. 1. Speed up Your Web Applicationswith HTML5 WebSocketsYakov Fain, Farata Systems, USA
  2. 2. The Plan- HTTP request-response- Demo- Server-Sent Events- Demo- WebSocket- Demo
  3. 3. What Do You See?
  4. 4. HTTP Hacks•  Polling•  Long Polling•  Streaming
  5. 5. Polling
  6. 6. Long PollingComet implementation: hanging GET or pending POST
  7. 7. Streaming
  8. 8. Getting Price Quotes from Google Finance
  9. 9. HTTP Request ResponseDemo
  10. 10. Introducing the DemoThe SoftwareThe Server:GlassFish 4 (promoted build B88), OracleThe server-side Java app can generate random price quotesThe Client:HTML5 Ext JS framework, SenchaThe Browser: Chrome , GoogleCharles ProxyThe Goal1. The server generates random stock prices for a 12-stock portfolio2. The user sends a request for price quote for a stock3. The HTML client displays the received price4. Observe what went over the network
  11. 11. The Server: Rest    @Path("stock")      public  class  RestResource  {              @GET              @Produces(value  =  MediaType.APPLICATION_JSON)              @Path("/{ticker}")              public  String  getRandomValue(@PathParam(value  =  "ticker")  String  ticker)  {                            return  new  Gson().toJson(RandomStocksGenerator.getDataForTicker(ticker));                        }      }      
  12. 12. The Client: AJAX in Ext JS        mypanel  button[action=doRestCall]:                    click:  this.onRestCall      onRestCall:  function(btn)  {      var  ticker  =  Ext.ComponentQuery.query(mypanel  textfield[name=ticker])[0].getValue();      var  rest_url  =  "http://"  +  document.location.host  +  document.location.pathname  +  "rest/stock/";      rest_url  =  rest_url  +  ticker;        Ext.Ajax.request({              url:  rest_url,              scope:  this,              success:  function(response)  {                      var  a  =  Ext.JSON.decode(response.responseText);                      a.price  =  parseFloat(a.price).toFixed(4);                      console.log(a);              }      });  }
  13. 13. Server-Sent Events
  14. 14. What’s SSE•  It’s not a request-response mode•  The browser subscribes to events from serverby creating EventSource pointing to this server•  The server can send data to client at any time•  The browser receives an event + data
  15. 15. Browser Subscribes to SSETo listen to any messages:  source.onmessage  =  function(e)  {….};  var  source  =  new  EventSource(http://localhost:8080/stock/events);    source.addEventListener(open,  function(e)  {      //  Connection  was  opened.  },  false);    source.addEventListener(priceChanged,  function(e)  {      var  priceQuote  =  JSON.parse(e.data);      //…  },  false);    source.addEventListener(error,  function(e)  {      if  (e.readyState  ==  EventSource.CLOSED)  {          //  Connection  was  closed.      }  },  false);  
  16. 16. Pushing SSE from ServerThe server sends events as text messages with MIMEtext/event-­‐stream    Each message starts with data: and end with a pair /n/n:data:  {"price":  "123.45"}/n/n  The browser concatenates all these messages separatingthem with /n.
  17. 17. Pushing from Glassfish (Jersey)@Path("stock")  public  class  SseResource  {      private  static  final  SseBroadcaster  BROADCASTER  =              new  SseBroadcaster();        private  boolean  isRunning  =  false;      private  Timer  broadcastTimer;        @GET      @Path("stock-­‐generator")      @Produces(SseFeature.SERVER_SENT_EVENTS)      public  EventOutput  itemEvents()  {          final  EventOutput  eventOutput  =  new  EventOutput();          BROADCASTER.add(eventOutput);          if  (!isRunning)  startBroadcastTask();          return  eventOutput;      }  }
  18. 18. Broadcasting in Jerseyprotected  void  startBroadcastTask()  {    broadcastTimer  =  new  Timer();    broadcastTimer    .schedule(new  SseBroadcastTask(BROADCASTER,  0),  0,  300);    this.isRunning  =  true;  }public  class  SseBroadcastTask  extends  TimerTask  {  private  final  SseBroadcaster  owner;    public  SseBroadcastTask(SseBroadcaster  owner,  int  timeout)  {      this.owner  =  owner;  }    @Override  public  void  run()  {      OutboundEvent  event  =  new  OutboundEvent.Builder().data(            String.class,  RandomStocksGenerator.getRandomValues().toJson()).build();      owner.broadcast(event);  
  19. 19. Push With Serer-Sent EventsDemo
  20. 20. Introducing the SSE DemoThe SoftwareThe Server:GlassFish 4 (promoted build B88), OracleThe Java app can generate random price quotesThe Client:HTML5 Ext JS framework, SenchaThe Chrome Browser, GoogleThe Goal1. The server generates random stock prices for a 12-stock portfolio2. The server pushes 3 price quotes per second using SSE3. The HTML client shows the prices in a data grid
  21. 21. WebSocket
  22. 22. WebSocket•  Standard W3C protocol (RFC6455)•  Java EE 7 includes WebSocket API (JSR-356)•  Web Browsers include window.WebSocketobject. No plugins required.
  23. 23. How WebSocket WorksEstablish a socket connection via HTTP for the initial handshake.Switch the protocol from HTTP to a socket-based protocol.Send messages in both directions simultaneously.This is not a request-response model!
  24. 24. Protocol Upgrade: HTTP à WebSocket•  Client sends Upgrade HTTP-request•  Server confirms Upgrade•  Client receives Upgrade response from server•  Client changes WebSocket.readyState to open
  25. 25. HTTP://… HTTPS://…WS://… WSS://…URI SchemesThe wss encryption is done the same way as in https
  26. 26. W3C: WebSocket Interface[Constructor(DOMString  url,  optional  (DOMString  or  DOMString[])  protocols)]  interface  WebSocket  :  EventTarget  {      readonly  attribute  DOMString  url;        const  unsigned  short  CONNECTING  =  0;                          const  unsigned  short  OPEN  =  1;      const  unsigned  short  CLOSING  =  2;      const  unsigned  short  CLOSED  =  3;      readonly  attribute  unsigned  short  readyState;      readonly  attribute  unsigned  long  bufferedAmount;        //  networking      [TreatNonCallableAsNull]  attribute  Function?  onopen;                  [TreatNonCallableAsNull]  attribute  Function?  onerror;      [TreatNonCallableAsNull]  attribute  Function?  onclose;      readonly  attribute  DOMString  extensions;      readonly  attribute  DOMString  protocol;                                              void  close([Clamp]  optional  unsigned  short  code,  optional  DOMString  reason);        //  messaging      [TreatNonCallableAsNull]  attribute  Function?  onmessage;                        attribute  DOMString  binaryType;      void  send(DOMString  data);                              void  send(ArrayBufferView  data);      void  send(Blob  data);  };
  27. 27. @ServerEndpoint in Java EEClientYour Java Endpointand other classesPOJODecoderEncoder
  28. 28. WebSocket Endpoint  @ServerEndpoint(value  =  "/stock-­‐generator",                  encoders  =  {  StockMessageEncoder.class  },                  decoders  =  {  StockMessageDecoder.class  })  public  class  StocksEndpoint  {            @OnOpen            public  void  onOpen(Session  session)  {                  …            }            @OnMessage          public  void  onMessage(StockMessage  message,  Session  client)  {            }              @OnClose            public  void  onClose(Session  session)  {…                  …              }          …  }
  29. 29. public  class  StockMessageDecoder  implements  Decoder.Text<StockMessage>  {          @Override        public  StockMessage  decode(String  s)  throws  DecodeException  {                Gson  gson  =  new  Gson();                return  gson.fromJson(s,  StockMessage.class);        }  }public  class  StockMessageEncoder  implements  Encoder.Text<StockMessage>  {                  @Override          public  String  encode(StockMessage  object)  throws  EncodeException  {                  return  new  Gson().toJson(object);          }  }DecoderEncoder
  30. 30. Heartbeats: Pings and PongsHeartbeats is a mechanism tocheck that connection is still alive.If a WebSocket implementationreceives a ping it hasto respond with a pong ASAP.There is no JavaScript API to support Pings and Pongs.
  31. 31. Web Socket Demo
  32. 32. The SoftwareThe Server:GlassFish 4 (promoted build B88), OracleThe Java app can generate random price quotesThe Client:HTML5 Ext JS framework, SenchaThe Chrome Browser, GoogleCharles proxyIntroducing the WebSocket DemoThe Goal1. The server generates random stock prices for a 12-stock portfolio2. The server pushes 20 price quotes per second using WebSocket3. The HTML client shows the prices in a data grid
  33. 33. What was Pushed via WebSocketThe size of each data push:The length price quote data: from 42 to 45 bytesWebSocket added overhead: 2 bytes{"symbol":  "APPL",  "id":  555,  "price":  "451.29"}  
  34. 34. Comparing OverheadsHttp Request-ResponseEach roundtrip has:request header: 429 bytes + 268 bytes response header+ 46 bytes dataServer-Sent EventsInitial request header 406 bytes + 268 bytes responseheaderEach push: 46 bytes data + 8 bytes message wrapperWebSocketInitial upgrade request: 406 bytes + 268 bytesEach push 46 bytes data + 2 bytes message wrapperIt’s full-duplex, not HTTP-based, works much faster.
  35. 35. Caniuse.com: Browser Support
  36. 36. Reducing kilobytes of data to 2 bytes...and reducing latency from 150ms to 50 msis far more than marginal.In fact, these two factors alone are enoughto make WebSocket seriously interesting toGoogle.Ian Hickson, GoogleThe lead HTML5 writer
  37. 37. Where to use WebSockets- Live trading/sports ticker- Controlling medical equipment over the web- Chat applications- Multiplayer online games- Real-time updating social streams
  38. 38. Unedited drafts of the book Enterprise Web Development are published atenterprisewebbook.com
  39. 39. Contact InfoFarata Systems: faratasystems.comPersonal blog: yakovfain.comTwitter: @yfainPodcasts in Russian: americhka.usThank you!

×