SlideShare a Scribd company logo
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 (20)

PDF
Angular 2 Essential Training
Patrick Schroeder
 
PPTX
Angular js 2
Ran Wahle
 
PPTX
Angular 5
Bartłomiej Narożnik
 
PDF
Web sockets in Angular
Yakov Fain
 
ODP
Introduction to Angular 2
Knoldus Inc.
 
PDF
Angular 2 - The Next Framework
Commit University
 
ODP
Angularjs
Vincenzo Ferrari
 
PDF
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Codemotion
 
PPTX
AngularJs presentation
Phan Tuan
 
PPTX
Angular 4
Saurabh Juneja
 
PDF
Reactive Thinking in Java with RxJava2
Yakov Fain
 
PDF
Angular 4 for Java Developers
Yakov Fain
 
PDF
Data Flow Patterns in Angular 2 - Sebastian Müller
Sebastian Holstein
 
PDF
Angular2 - In Action
Sebastian Pożoga
 
PPTX
Angular2 for Beginners
Oswald Campesato
 
PDF
Commit University - Exploring Angular 2
Commit University
 
PDF
AngularJS application architecture
Gabriele Falace
 
PDF
RESTful services and OAUTH protocol in IoT
Yakov Fain
 
PPTX
Async patterns in javascript
Ran Wahle
 
PDF
Create Your Own Framework by Fabien Potencier
Himel Nag Rana
 
Angular 2 Essential Training
Patrick Schroeder
 
Angular js 2
Ran Wahle
 
Web sockets in Angular
Yakov Fain
 
Introduction to Angular 2
Knoldus Inc.
 
Angular 2 - The Next Framework
Commit University
 
Angularjs
Vincenzo Ferrari
 
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Codemotion
 
AngularJs presentation
Phan Tuan
 
Angular 4
Saurabh Juneja
 
Reactive Thinking in Java with RxJava2
Yakov Fain
 
Angular 4 for Java Developers
Yakov Fain
 
Data Flow Patterns in Angular 2 - Sebastian Müller
Sebastian Holstein
 
Angular2 - In Action
Sebastian Pożoga
 
Angular2 for Beginners
Oswald Campesato
 
Commit University - Exploring Angular 2
Commit University
 
AngularJS application architecture
Gabriele Falace
 
RESTful services and OAUTH protocol in IoT
Yakov Fain
 
Async patterns in javascript
Ran Wahle
 
Create Your Own Framework by Fabien Potencier
Himel Nag Rana
 

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

PPTX
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
C2B2 Consulting
 
PPTX
Fight empire-html5
Bhakti Mehta
 
PDF
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
PPT
Web-Socket
Pankaj Kumar Sharma
 
PPTX
Scalableenterpriseapplicationswith jee7andbeyond
Andy Moncsek
 
PPT
JUG louvain websockets
Marc Tritschler
 
PPTX
WebSockets in JEE 7
Shahzad Badar
 
PDF
Lecture 6 Web Sockets
Fahad Golra
 
PDF
WebSocket Push Fallback - Transcript.pdf
ShaiAlmog1
 
ODP
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Masoud Kalali
 
PPTX
Web sockets in Java
Pance Cavkovski
 
PDF
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
David Delabassee
 
PDF
WebSockets with Spring 4
Sergi Almar i Graupera
 
PDF
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Codemotion
 
PDF
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
jaxLondonConference
 
PDF
Getting Started with WebSockets and Server-Sent Events
Arun Gupta
 
PPTX
Enhancing Mobile User Experience with WebSocket
Mauricio "Maltron" Leal
 
PPTX
Asynchronous Web Programming with HTML5 WebSockets and Java
James Falkner
 
PDF
Real-Time with Flowdock
Flowdock
 
PDF
WebSockets - Realtime em Mundo Conectado
Bruno Borges
 
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
C2B2 Consulting
 
Fight empire-html5
Bhakti Mehta
 
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
Scalableenterpriseapplicationswith jee7andbeyond
Andy Moncsek
 
JUG louvain websockets
Marc Tritschler
 
WebSockets in JEE 7
Shahzad Badar
 
Lecture 6 Web Sockets
Fahad Golra
 
WebSocket Push Fallback - Transcript.pdf
ShaiAlmog1
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Masoud Kalali
 
Web sockets in Java
Pance Cavkovski
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
David Delabassee
 
WebSockets with Spring 4
Sergi Almar i Graupera
 
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Codemotion
 
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
jaxLondonConference
 
Getting Started with WebSockets and Server-Sent Events
Arun Gupta
 
Enhancing Mobile User Experience with WebSocket
Mauricio "Maltron" Leal
 
Asynchronous Web Programming with HTML5 WebSockets and Java
James Falkner
 
Real-Time with Flowdock
Flowdock
 
WebSockets - Realtime em Mundo Conectado
Bruno Borges
 
Ad

More from Yakov Fain (15)

PDF
Type script for_java_dev_jul_2020
Yakov Fain
 
PDF
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
PDF
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
PDF
TypeScript for Java Developers
Yakov Fain
 
PDF
Reactive Streams and RxJava2
Yakov Fain
 
PDF
Using JHipster 4 for generating Angular/Spring Boot apps
Yakov Fain
 
PDF
Reactive programming in Angular 2
Yakov Fain
 
PDF
Reactive Thinking in Java
Yakov Fain
 
PDF
Angular 2 for Java Developers
Yakov Fain
 
PDF
Integrating consumers IoT devices into Business Workflow
Yakov Fain
 
PDF
Java Intro: Unit1. Hello World
Yakov Fain
 
PDF
Running a Virtual Company
Yakov Fain
 
PDF
Princeton jug git_github
Yakov Fain
 
PDF
Surviving as a Professional Software Developer
Yakov Fain
 
PDF
Becoming a professional software developer
Yakov Fain
 
Type script for_java_dev_jul_2020
Yakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
Using JHipster for generating Angular/Spring Boot apps
Yakov Fain
 
TypeScript for Java Developers
Yakov Fain
 
Reactive Streams and RxJava2
Yakov Fain
 
Using JHipster 4 for generating Angular/Spring Boot apps
Yakov Fain
 
Reactive programming in Angular 2
Yakov Fain
 
Reactive Thinking in Java
Yakov Fain
 
Angular 2 for Java Developers
Yakov Fain
 
Integrating consumers IoT devices into Business Workflow
Yakov Fain
 
Java Intro: Unit1. Hello World
Yakov Fain
 
Running a Virtual Company
Yakov Fain
 
Princeton jug git_github
Yakov Fain
 
Surviving as a Professional Software Developer
Yakov Fain
 
Becoming a professional software developer
Yakov Fain
 
Ad

Recently uploaded (20)

PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Digital Circuits, important subject in CS
contactparinay1
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 

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!