SlideShare a Scribd company logo
1 of 40
Speed up Your Web Applications
with HTML5 WebSockets
Yakov Fain, Farata Systems, USA
Speed up your Web applications with HTML5 WebSockets
The Plan
- HTTP request-response
- Demo
- Server-Sent Events
- Demo
- WebSocket
- Demo
What Do You See?
HTTP Hacks
•  Polling
•  Long Polling
•  Streaming
Polling
Long Polling
Comet implementation: hanging GET or pending POST
Streaming
Getting Price Quotes from Google Finance
HTTP Request Response
Demo
Introducing the Demo
The Software
The Server:
GlassFish 4 (promoted build B88), Oracle
The server-side Java app can generate random price quotes
The Client:
HTML5 Ext JS framework, Sencha
The Browser: Chrome , Google
Charles Proxy
The Goal
1. The server generates random stock prices for a 12-stock portfolio
2. The user sends a request for price quote for a stock
3. The HTML client displays the received price
4. Observe what went over the network
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));	
  
	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  }	
  
	
  	
  }	
  
	
  	
  
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);	
  
	
  	
  	
  	
  	
  	
  }	
  
	
  	
  });	
  
}
Server-Sent Events
What’s SSE
•  It’s not a request-response mode
•  The browser subscribes to events from server
by creating EventSource pointing to this server
•  The server can send data to client at any time
•  The browser receives an event + data
Browser Subscribes to SSE
To 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);	
  
Pushing SSE from Server
The server sends events as text messages with MIME
text/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 separating
them with /n.
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;	
  
	
  	
  }	
  
}
Broadcasting in Jersey
protected	
  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);	
  
Push With Serer-Sent Events
Demo
Introducing the SSE Demo
The Software
The Server:
GlassFish 4 (promoted build B88), Oracle
The Java app can generate random price quotes
The Client:
HTML5 Ext JS framework, Sencha
The Chrome Browser, Google
The Goal
1. The server generates random stock prices for a 12-stock portfolio
2. The server pushes 3 price quotes per second using SSE
3. The HTML client shows the prices in a data grid
WebSocket
WebSocket
•  Standard W3C protocol (RFC6455)
•  Java EE 7 includes WebSocket API (JSR-356)
•  Web Browsers include window.WebSocket
object. No plugins required.
How WebSocket Works
Establish 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!
Protocol Upgrade: HTTP à WebSocket
•  Client sends Upgrade HTTP-request
•  Server confirms Upgrade
•  Client receives Upgrade response from server
•  Client changes WebSocket.readyState to open
HTTP://… HTTPS://…
WS://… WSS://…
URI Schemes
The wss encryption is done the same way as in https
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);	
  
};
@ServerEndpoint in Java EE
Client
Your Java Endpoint
and other classes
POJO
Decoder
Encoder
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)	
  {…	
  
	
  	
  	
  	
  	
  	
  	
  	
  …	
  
	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  …	
  
}
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);	
  
	
  	
  	
  	
  }	
  
}
Decoder
Encoder
Heartbeats: Pings and Pongs
Heartbeats is a mechanism to
check that connection is still alive.
If a WebSocket implementation
receives a ping it has
to respond with a pong ASAP.
There is no JavaScript API to support Pings and Pongs.
Web Socket Demo
The Software
The Server:
GlassFish 4 (promoted build B88), Oracle
The Java app can generate random price quotes
The Client:
HTML5 Ext JS framework, Sencha
The Chrome Browser, Google
Charles proxy
Introducing the WebSocket Demo
The Goal
1. The server generates random stock prices for a 12-stock portfolio
2. The server pushes 20 price quotes per second using WebSocket
3. The HTML client shows the prices in a data grid
What was Pushed via WebSocket
The size of each data push:
The length price quote data: from 42 to 45 bytes
WebSocket added overhead: 2 bytes
{"symbol":	
  "APPL",	
  "id":	
  555,	
  "price":	
  "451.29"}	
  
Comparing Overheads
Http Request-Response
Each roundtrip has:
request header: 429 bytes + 268 bytes response header
+ 46 bytes data
Server-Sent Events
Initial request header 406 bytes + 268 bytes response
header
Each push: 46 bytes data + 8 bytes message wrapper
WebSocket
Initial upgrade request: 406 bytes + 268 bytes
Each push 46 bytes data + 2 bytes message wrapper
It’s full-duplex, not HTTP-based, works much faster.
Caniuse.com: Browser Support
Reducing kilobytes of data to 2 bytes...
and reducing latency from 150ms to 50 ms
is far more than marginal.
In fact, these two factors alone are enough
to make WebSocket seriously interesting to
Google.
Ian Hickson, Google
The lead HTML5 writer
Where to use WebSockets
- Live trading/sports ticker
- Controlling medical equipment over the web
- Chat applications
- Multiplayer online games
- Real-time updating social streams
Unedited drafts of the book Enterprise Web Development are published at
enterprisewebbook.com
Contact Info
Farata Systems: faratasystems.com
Personal blog: yakovfain.com
Twitter: @yfain
Podcasts in Russian: americhka.us
Thank you!

More Related Content

What's hot

Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training Patrick Schroeder
 
Angular js 2
Angular js 2Angular js 2
Angular js 2Ran Wahle
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in AngularYakov Fain
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Knoldus Inc.
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next FrameworkCommit University
 
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016Codemotion
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation Phan Tuan
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Yakov Fain
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
 
Data Flow Patterns in Angular 2 - Sebastian Müller
Data Flow Patterns in Angular 2 -  Sebastian MüllerData Flow Patterns in Angular 2 -  Sebastian Müller
Data Flow Patterns in Angular 2 - Sebastian MüllerSebastian Holstein
 
Commit University - Exploring Angular 2
Commit University - Exploring Angular 2Commit University - Exploring Angular 2
Commit University - Exploring Angular 2Commit University
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architectureGabriele Falace
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTYakov Fain
 
Async patterns in javascript
Async patterns in javascriptAsync patterns in javascript
Async patterns in javascriptRan Wahle
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierHimel Nag Rana
 

What's hot (20)

Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
 
Angular 5
Angular 5Angular 5
Angular 5
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
 
Angularjs
AngularjsAngularjs
Angularjs
 
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 
Angular 4
Angular 4Angular 4
Angular 4
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Data Flow Patterns in Angular 2 - Sebastian Müller
Data Flow Patterns in Angular 2 -  Sebastian MüllerData Flow Patterns in Angular 2 -  Sebastian Müller
Data Flow Patterns in Angular 2 - Sebastian Müller
 
Angular2 - In Action
Angular2  - In ActionAngular2  - In Action
Angular2 - In Action
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
Commit University - Exploring Angular 2
Commit University - Exploring Angular 2Commit University - Exploring Angular 2
Commit University - Exploring Angular 2
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architecture
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoT
 
Async patterns in javascript
Async patterns in javascriptAsync patterns in javascript
Async patterns in javascript
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien Potencier
 

Similar to Speed up your Web applications with HTML5 WebSockets

Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwrdeimos
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authenticationWindowsPhoneRocks
 
DWR, Hibernate and Dojo.E - A Tutorial
DWR, Hibernate and Dojo.E - A TutorialDWR, Hibernate and Dojo.E - A Tutorial
DWR, Hibernate and Dojo.E - A Tutorialjbarciauskas
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client servertrilestari08
 
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump StartHaim Michael
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websocketsWim Godden
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Ismael Celis
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Paco de la Cruz
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelChapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelCSDeptSriKaliswariCo
 
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...Yoshifumi Kawai
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)Ghadeer AlHasan
 

Similar to Speed up your Web applications with HTML5 WebSockets (20)

Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
 
Network
NetworkNetwork
Network
 
DWR, Hibernate and Dojo.E - A Tutorial
DWR, Hibernate and Dojo.E - A TutorialDWR, Hibernate and Dojo.E - A Tutorial
DWR, Hibernate and Dojo.E - A Tutorial
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client server
 
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump Start
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 
Servlets
ServletsServlets
Servlets
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelChapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & Deitel
 
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)
 

More from Yakov Fain

Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Yakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsYakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsYakov Fain
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2Yakov Fain
 
Using JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsUsing JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsYakov Fain
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2Yakov Fain
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in JavaYakov Fain
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowYakov Fain
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldYakov Fain
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual CompanyYakov Fain
 
Princeton jug git_github
Princeton jug git_githubPrinceton jug git_github
Princeton jug git_githubYakov Fain
 
Surviving as a Professional Software Developer
Surviving as a Professional Software DeveloperSurviving as a Professional Software Developer
Surviving as a Professional Software DeveloperYakov Fain
 
Becoming a professional software developer
Becoming a professional software developerBecoming a professional software developer
Becoming a professional software developerYakov Fain
 

More from Yakov Fain (15)

Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2
 
Using JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsUsing JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot apps
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business Workflow
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello World
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual Company
 
Princeton jug git_github
Princeton jug git_githubPrinceton jug git_github
Princeton jug git_github
 
Surviving as a Professional Software Developer
Surviving as a Professional Software DeveloperSurviving as a Professional Software Developer
Surviving as a Professional Software Developer
 
Becoming a professional software developer
Becoming a professional software developerBecoming a professional software developer
Becoming a professional software developer
 

Recently uploaded

Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024Brian Pichman
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Alkin Tezuysal
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
Graphene Quantum Dots-Based Composites for Biomedical Applications
Graphene Quantum Dots-Based Composites for  Biomedical ApplicationsGraphene Quantum Dots-Based Composites for  Biomedical Applications
Graphene Quantum Dots-Based Composites for Biomedical Applicationsnooralam814309
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNeo4j
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingFrancesco Corti
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfTejal81
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.IPLOOK Networks
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4DianaGray10
 
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2DianaGray10
 
How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxKaustubhBhavsar6
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FESTBillieHyde
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxNeo4j
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfInfopole1
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0DanBrown980551
 

Recently uploaded (20)

Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
Graphene Quantum Dots-Based Composites for Biomedical Applications
Graphene Quantum Dots-Based Composites for  Biomedical ApplicationsGraphene Quantum Dots-Based Composites for  Biomedical Applications
Graphene Quantum Dots-Based Composites for Biomedical Applications
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4j
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is going
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4
 
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2
 
How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptx
 
SheDev 2024
SheDev 2024SheDev 2024
SheDev 2024
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FEST
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdf
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0
 

Speed up your Web applications with HTML5 WebSockets

  • 1. Speed up Your Web Applications with HTML5 WebSockets Yakov Fain, Farata Systems, USA
  • 3. The Plan - HTTP request-response - Demo - Server-Sent Events - Demo - WebSocket - Demo
  • 4. What Do You See?
  • 5. HTTP Hacks •  Polling •  Long Polling •  Streaming
  • 7. Long Polling Comet implementation: hanging GET or pending POST
  • 9. Getting Price Quotes from Google Finance
  • 11. Introducing the Demo The Software The Server: GlassFish 4 (promoted build B88), Oracle The server-side Java app can generate random price quotes The Client: HTML5 Ext JS framework, Sencha The Browser: Chrome , Google Charles Proxy The Goal 1. The server generates random stock prices for a 12-stock portfolio 2. The user sends a request for price quote for a stock 3. The HTML client displays the received price 4. Observe what went over the network
  • 12. 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));                        }      }      
  • 13. 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);              }      });   }
  • 15. What’s SSE •  It’s not a request-response mode •  The browser subscribes to events from server by creating EventSource pointing to this server •  The server can send data to client at any time •  The browser receives an event + data
  • 16. Browser Subscribes to SSE To 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);  
  • 17. Pushing SSE from Server The server sends events as text messages with MIME text/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 separating them with /n.
  • 18. 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;      }   }
  • 19. Broadcasting in Jersey protected  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);  
  • 20. Push With Serer-Sent Events Demo
  • 21. Introducing the SSE Demo The Software The Server: GlassFish 4 (promoted build B88), Oracle The Java app can generate random price quotes The Client: HTML5 Ext JS framework, Sencha The Chrome Browser, Google The Goal 1. The server generates random stock prices for a 12-stock portfolio 2. The server pushes 3 price quotes per second using SSE 3. The HTML client shows the prices in a data grid
  • 23. WebSocket •  Standard W3C protocol (RFC6455) •  Java EE 7 includes WebSocket API (JSR-356) •  Web Browsers include window.WebSocket object. No plugins required.
  • 24. How WebSocket Works Establish 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!
  • 25. Protocol Upgrade: HTTP à WebSocket •  Client sends Upgrade HTTP-request •  Server confirms Upgrade •  Client receives Upgrade response from server •  Client changes WebSocket.readyState to open
  • 26. HTTP://… HTTPS://… WS://… WSS://… URI Schemes The wss encryption is done the same way as in https
  • 27. 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);   };
  • 28. @ServerEndpoint in Java EE Client Your Java Endpoint and other classes POJO Decoder Encoder
  • 29. 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)  {…                  …              }          …   }
  • 30. 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);          }   } Decoder Encoder
  • 31. Heartbeats: Pings and Pongs Heartbeats is a mechanism to check that connection is still alive. If a WebSocket implementation receives a ping it has to respond with a pong ASAP. There is no JavaScript API to support Pings and Pongs.
  • 33. The Software The Server: GlassFish 4 (promoted build B88), Oracle The Java app can generate random price quotes The Client: HTML5 Ext JS framework, Sencha The Chrome Browser, Google Charles proxy Introducing the WebSocket Demo The Goal 1. The server generates random stock prices for a 12-stock portfolio 2. The server pushes 20 price quotes per second using WebSocket 3. The HTML client shows the prices in a data grid
  • 34. What was Pushed via WebSocket The size of each data push: The length price quote data: from 42 to 45 bytes WebSocket added overhead: 2 bytes {"symbol":  "APPL",  "id":  555,  "price":  "451.29"}  
  • 35. Comparing Overheads Http Request-Response Each roundtrip has: request header: 429 bytes + 268 bytes response header + 46 bytes data Server-Sent Events Initial request header 406 bytes + 268 bytes response header Each push: 46 bytes data + 8 bytes message wrapper WebSocket Initial upgrade request: 406 bytes + 268 bytes Each push 46 bytes data + 2 bytes message wrapper It’s full-duplex, not HTTP-based, works much faster.
  • 37. Reducing kilobytes of data to 2 bytes... and reducing latency from 150ms to 50 ms is far more than marginal. In fact, these two factors alone are enough to make WebSocket seriously interesting to Google. Ian Hickson, Google The lead HTML5 writer
  • 38. Where to use WebSockets - Live trading/sports ticker - Controlling medical equipment over the web - Chat applications - Multiplayer online games - Real-time updating social streams
  • 39. Unedited drafts of the book Enterprise Web Development are published at enterprisewebbook.com
  • 40. Contact Info Farata Systems: faratasystems.com Personal blog: yakovfain.com Twitter: @yfain Podcasts in Russian: americhka.us Thank you!