SlideShare uma empresa Scribd logo
1 de 52
Fight the empire light weightly with
HTML5, WebSockets, Server-sent
Events and others
Bhakti Mehta
Twitter: @bhakti_mehta
Introduction
• Currently working as a Senior Software Engineer at
Blue Jeans Network. Bluejeans.com
• Worked at Sun Microsystems/Oracle for 13 years
• Committer to numerous open source projects
• Author of Developing RESTful Services with JAX-RS
2.0, WebSockets and JSON
Copyright 2013, Bhakti Mehta all rights reserved
Fight the empire!
Copyright 2013, Bhakti Mehta all rights reserved
Agenda
 Introduction
 Polling
 Server- sent Events (SSE)
 WebSockets
 JAXRS 2.0
 JSON-P
Copyright 2013, Bhakti Mehta all rights reserved
Polling
 Used by vast majority of AJAX applications
 Poll the server for data
 Client --->request--> Server
 If no data empty response is returned
Copyright 2013, Bhakti Mehta all rights reserved
Polling
Copyright 2013, Bhakti Mehta all rights reserved
Client Server
Request (client_id)
Response 200 OK: empty
Request (client_id)
….
….
….
….
Response 200 OK: message
body
Polling Drawbacks
 Http overhead
 Reducing the interval will consume more bandwidth
and processing resources for nothing.
Copyright 2013, Bhakti Mehta all rights reserved
Long Polling
 If server does not have data holds request open
 COMET
 Chunked transfer encoding can be used to send
chunks of data as part of response body which is
opened as a stream.
 Chunks can be javascript tags loaded in hidden
iframe and executed in order of arrival
Copyright 2013, Bhakti Mehta all rights reserved
Long Polling
Copyright 2013, Bhakti Mehta all rights reserved
Client Server
Request (client_id)
Response 200 OK: message body
Request (client_id)
….
….
….
Response 200 OK: message
body
….
….
Long Polling Drawbacks
• One-way communication
• No standard data format or message format when
used in chunked transfer encoding mode
• Each connection initiation has the initiation cost.
• No caching between clients and server, which
impacts the server performance instead of reading
some contents from the cache.
Copyright 2013, Bhakti Mehta all rights reserved
Server-sent events
Copyright 2013, Bhakti Mehta all rights reserved
 Unidirectional channel between server and client
 Server pushes data to your app when it wants
 Updates can be streamed from server to client as they
happen
Server-sent Events
Copyright 2013, Bhakti Mehta all rights reserved
Client Server
Request (client_id)
….
….
….
SSE message
….
….
SSE message
Server-sent Events
 Subscribing to event stream
To subscribe to an event stream, create an EventSource
object and pass it the URL of your stream:
Example in javascript
eventSource = new EventSource(url);
eventSource.onmessage = function (event) {
}
 Setting up handlers for events
You can optionally listen for onopen() and onerror()
functions
Copyright 2013, Bhakti Mehta all rights reserved
Message format for SSE
 Sending an event stream
 Construct a plaintext response, served with a
text/event-stream Content-Type.
 Sample message format
 data: Help me Obi Wan-Kenobi you are my only
hopenn
Copyright 2013, Bhakti Mehta all rights reserved
Server-sent Events and
JSON
 Sending JSON
You can send multiple lines without breaking JSON
format by sending messages like this
data: {nn
data: "name": Luke Skywalker",nn
data: ”home": Tatooinenn
data: }nn
 On client side
source.addEventListener('message', function(e) {
var data = JSON.parse(e.data);
Copyright 2013, Bhakti Mehta all rights reserved
Associating event names
with SSE
event: order66Issuedn
data: {“issuer” : “Chancellor Palpatine”}nn
event: jedisPurgedn
data: {“survivor” :”Obi-Wan Kenobi, Yoda”}nn
Copyright 2013, Bhakti Mehta all rights reserved
Associating ids with SSE
Associating ids with events can help with fault
tolerance in SSE
id: 123 n
data: Battle of droids deployed at Naboonn
Copyright 2013, Bhakti Mehta all rights reserved
Connection loss and
retries
• Browsers that support SSE can try reconnecting to
the server in case the connection between browser
and server is severed. The default retry interval is
3000 milliseconds but it can be adjusted by
including the retry directive in the messages that
server sends to the client.
• For example to increase the retry interval to 5000
milliseconds SSE message that server sends can be
similar to the following listing:
retry: 5000n
data: This is a single line datann
Copyright 2013, Bhakti Mehta all rights reserved
Server-sent Events and
reconnection
 If the connection drops, the EventSource fires an
error event and automatically tries to reconnect.
 The server can also control the timeout before the
client tries to reconnect.
Copyright 2013, Bhakti Mehta all rights reserved
Best practices for Server-
sent Events
 Check if eventSource's origin attribute is the
expected domain to get the message
if (e.origin != 'http://foo.com') {
alert('Origin was not http://foo.com');
return;
Copyright 2013, Bhakti Mehta all rights reserved
Best practices for Server-
sent Events
 Associating an ID with an event
Setting an ID lets the browser keep track of the last
event fired
 Incase connection is dropped a special Last-
Event-ID is set with new request
 This lets the browser determine which event is
appropriate to fire. The message event contains
a e.lastEventId property.
Copyright 2013, Bhakti Mehta all rights reserved
Comparing Polling vs
Long Polling vs SSE
 Polling: GET. If data, process data. GET...
1 GET = 1 HTTP response header and maybe a chunk of
data.
 Long-polling: GET. Wait. Process data. GET...
1 GET = 1 HTTP response header and chunks of data.
 SSE: GET. Wait. Process data. Wait. Process data. Wait...
1 GET = 1 HTTP response header and chunks of data with
small headers
Copyright 2013, Bhakti Mehta all rights reserved
WebSockets
 Full duplex communication in either direction
 Data is framed with 2 bytes
 In the case of text frames, each frame starts with a
0x00 byte, ends with a 0xFF byte, and contains UTF-8
data in between.
Copyright 2013, Bhakti Mehta all rights reserved
WebSockets
 Client and Server upgrade from Http protocol to
WebSocket protocol during initial handshake
GET /text HTTP/1.1rn
Upgrade: WebSocketrn
Connection: Upgradern
Host: www.websocket.orgrn …rn
 Handshake from server looks like
HTTP/1.1 101 WebSocket Protocol Handshakern
Upgrade: WebSocketrn
Connection: Upgradern …rn
Copyright 2013, Bhakti Mehta all rights reserved
WebSockets Handshake
Copyright 2013, Bhakti Mehta all rights reserved
WebSockets
 After the upgrade HTTP is completely out of the
picture at this point.
 Using the lightweight WebSocket wire protocol,
messages can now be sent or received by either
endpoint at any time.
 Creating a Websocket
 ws = new WebSocket("ws://localhost:8080/../WebSocketChat");
 You can set handlers for events onopen or onerror
Copyright 2013, Bhakti Mehta all rights reserved
WebSockets JSR 356
 @ServerEndpoint
signifies that the Java class it decorates is to be
deployed as WebSocket endpoint
 Additionally the following components can be
annotated with @ServerEndpoint
 a stateless session EJB
 a singleton EJB
 a CDI managed bean
Copyright 2013, Bhakti Mehta all rights reserved
WebSockets and Security
 A web socket which is mapped to a given ws://
URI is protected in the deployment descriptor with a
listing to a http:// URI with same hostname, port and
path
since this is the URL of its opening handshake
Copyright 2013, Bhakti Mehta all rights reserved
Comparisons
Subject SSE WebSockets Long Polling
Error Handling Built in support Built in support Almost no error
handling in
chunked transfer
Performance Better than long
polling and
inferior to
WebSockets
Best performance Small CPU
resource but idle
process/thread
per client
connection limits
scalability
Communication
channel
HTTP
unidirectional
WebSockets
bidirectional
Http
unidirectional
Copyright 2013, Bhakti Mehta all rights reserved
Comparisons
Subject SSE WebSockets Long Polling
Implementation
complexity
Easy Requires
websocket
support
Easiest
Browser Support Firefox,Chrome
Safari, Opera
For RFC 6455: IE
10, Firefox 11,
Chrome 16, Safari
6, Opera 12.10
All current
browsers
Copyright 2013, Bhakti Mehta all rights reserved
Best practices for
WebSockets
• Throttling the rate of sending data
• The WebSockets has a bufferedAmount attribute
which can be used to control the rate of sending
data. Using the bufferedAmount attribute you can
check the number of bytes that have been queue
but not yet sent to the server.
if (webSocket.bufferedAmount < THRESHOLD)
webSocket.send(someData);
};
Copyright 2013, Bhakti Mehta all rights reserved
Best practices for
WebSockets
• Controlling the maximum size of the message
• Use the maxMessageSize attribute on @OnMessage
annotation
• If the incoming message exceeds the maximum size
then the connection is closed. This is a good
practice to control the maximum size of a message
so that the client does not deplete its resources
trying to handle a message, which it can’t process.
Copyright 2013, Bhakti Mehta all rights reserved
Best practices for
WebSockets
• Use wss protocol with Proxy servers
• Proxy servers may not allow unencrypted Web
Socket traffic to flow through. Since the traffic is
encrypted there is a greater chance to pass
through the proxy server.
• Then the CONNECT statements will work and there
will be an end-to-end encrypted tunnel for web
sockets.
Copyright 2013, Bhakti Mehta all
rights reserved
Best practices for
WebSockets
Copyright 2013, Bhakti Mehta all rights reserved
Client1
Client2
Client3
RESTful Webservices
• Key principles of REST
• Associating IDs to resources
• Using standard HTTP methods
• Multiple formats data sent by a resource
• Statelessness
Copyright 2013, Bhakti Mehta all rights reserved
RESTful WebServices
• GET: The GET request retrieves a representation of a
resource from server to client.
• POST: The POST request is used to create a resource
on the server based on the representation that the
client sends.
• PUT: The PUT request is used to update or create a
reference to a resource on server.
• DELETE: The DELETE request can delete a resource
on server.
• HEAD: The HEAD requests checks for a resource
without retrieving it.
Copyright 2013, Bhakti Mehta all rights reserved
RESTful WebServices
• Safety
o Invoking a method does not change the
resource on server
o GET, HEAD are safe
o PUT, DELETE, POST are not safe
• Idempotence
o Calling a method multiple times will not change
the result
o GET, HEAD, PUT,DELETE are idempotent
o POST is not idempotent
Copyright 2013, Bhakti Mehta all rights reserved
JAX-RS 2.0
Defines how to expose POJOs as web resources,
using HTTP as the network protocol.
Applications using these APIs can be deployed to
an application server in a portable manner.
Copyright 2013, Bhakti Mehta all rights reserved
Resources and JAX-RS
1.Define a root resource
@Path(”jedis")
public class JediResource {
}
2. Define methods for resource and mime type
@GET
@Produces(“text/plain”)
public String getRank() {
return rank; // for eg Youngling, Padawan, Jedi Knight or Jedi
Master
}
Copyright 2013, Bhakti Mehta all rights reserved
SubResources and JAX-RS
1.Define a sub resource
@Path("/jedis")
public class JediResource {
@Path(”/jedi/{name}")
public Jedi getJedi(@PathParam(”name") String name){
//return Jedi
}
public class Jedi {
@Path(”/apprentice")
public String getApprentice(){
}
}
Copyright 2013, Bhakti Mehta all rights reserved
SubResources and JAX-RS
• If request is GET /jedis/Yodas
• The JediResource.getJedi() method will be invoked.
• If a client sends a request using the URI
• GET /jedis/Yoda/apprentice
• Jedi object is returned and getApprentice()
method is invoked
Copyright 2013, Bhakti Mehta all rights reserved
Client API for JAX-RS 2.0
• Client client = ClientBuilder.newClient();
• WebTarget target = client.target(URI);
• String jedi = target.request().get(String.class);
Copyright 2013, Bhakti Mehta all rights reserved
JAX-RS 2.0
 Client API
 Filters and Interceptors
 Client-side and Server-side Asynchronous
 Improved Connection Negotiation
 Alignment with JSR 330
Copyright 2013, Bhakti Mehta all rights reserved
Java API for JSON
Processing JSON-P
 Streaming API to produce/consume JSON
 Similar to StAX API in XML world
 Object model API to represent JSON
 Similar to DOM API in XML world
Copyright 2013, Bhakti Mehta all rights reserved
JsonParser
 JsonParser – Parses JSON in a streaming way from
input sources
 Similar to StAX’s XMLStreamReader, a pull parser
 Created
 Parser state events :
START_ARRAY, START_OBJECT, KEY_NAME, VALUE_STRING,
VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, VALUE_NULL,
END_OBJECT, END_ARRAY
 Created using :
Json.createParser(…),
Json.createParserFactory().createParser(…)
Copyright 2013, Bhakti Mehta all rights reserved
JsonGenerator
 JsonGenerator – Generates JSON in a streaming
way to output sources
 Similar to StAX’s XMLStreamWriter
 Created using :
Json.createGenerator(…),
Json.createGeneratorFactory().createGenerator(…)
Copyright 2013, Bhakti Mehta all rights reserved
JsonReader
 Reads JsonObject and JsonArray from
input source
 Uses pluggable JsonParser
try (JsonReader reader = new JsonReader(io)) {
JsonObject obj = reader.readObject();
}
Copyright 2013, Bhakti Mehta all rights reserved
JsonWriter
 Writes JsonObject and JsonArray to
output source
 Uses pluggable JsonGenerator
// Writes a JSON object
try (JsonWriter writer = new JsonWriter(io)) {
writer.writeObject(obj);
}
Copyright 2013, Bhakti Mehta all rights reserved
JSON sample data
{
”name": "Jar Jar Binks”, ”home": “Naboo”,
”affilitation": [
{ "type": ”primary", "name": ”Royal
House of Naboo" },
{ "type": ”secondary", "name":
”Galactic republic" }]}
]
}
Copyright 2013, Bhakti Mehta all rights reserved
Call for action
• Download GlassFish 4.0 from glassfish.dev.java.net
• File issues, contribute patches
• Email users@glassfish.dev.java.net
Copyright 2013, Bhakti Mehta all rights reserved
Questions
• Twitter: @bhakti_mehta
• Blog https://www.java.net//blogs/bhaktimehta
• LinkedIn: http://www.linkedin.com/in/bhaktihmehta
• May the force be with you!!
Copyright 2013, Bhakti Mehta all rights reserved
Copyright 2013, Bhakti Mehta all
rights reserved

Mais conteúdo relacionado

Mais procurados

Http - All you need to know
Http - All you need to knowHttp - All you need to know
Http - All you need to knowGökhan Şengün
 
05 20254 financial stock application
05 20254 financial stock application05 20254 financial stock application
05 20254 financial stock applicationIAESIJEECS
 
Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)maamir farooq
 
Scalable Reliable Secure REST
Scalable Reliable Secure RESTScalable Reliable Secure REST
Scalable Reliable Secure RESTguestb2ed5f
 
Decoding real time web communication
Decoding real time web communicationDecoding real time web communication
Decoding real time web communicationAMiT JAiN
 
Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Navaneethan Naveen
 
Http basics by-joshi_29_4_15-ppt
Http basics by-joshi_29_4_15-pptHttp basics by-joshi_29_4_15-ppt
Http basics by-joshi_29_4_15-pptQwinix Technologies
 
21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboardsDenis Ristic
 
HTTP fundamentals for developers
HTTP fundamentals for developersHTTP fundamentals for developers
HTTP fundamentals for developersMario Cardinal
 
Web Performance Hacks
Web Performance HacksWeb Performance Hacks
Web Performance HacksSagar Desarda
 
Web (HTTP) request to response life cycle
Web (HTTP) request to response life cycleWeb (HTTP) request to response life cycle
Web (HTTP) request to response life cycleGopakumar Kunduveetil
 
UOW-Caching and new ways to improve response time (Paper)
UOW-Caching and new ways to improve response time (Paper)UOW-Caching and new ways to improve response time (Paper)
UOW-Caching and new ways to improve response time (Paper)Guson Kuntarto
 
A SURVEY ON WEB PRE-FETCHING AND WEB CACHING TECHNIQUES IN A MOBILE ENVIRONMENT
A SURVEY ON WEB PRE-FETCHING AND WEB CACHING TECHNIQUES IN A MOBILE ENVIRONMENTA SURVEY ON WEB PRE-FETCHING AND WEB CACHING TECHNIQUES IN A MOBILE ENVIRONMENT
A SURVEY ON WEB PRE-FETCHING AND WEB CACHING TECHNIQUES IN A MOBILE ENVIRONMENTcscpconf
 

Mais procurados (20)

Http
HttpHttp
Http
 
Http - All you need to know
Http - All you need to knowHttp - All you need to know
Http - All you need to know
 
05 20254 financial stock application
05 20254 financial stock application05 20254 financial stock application
05 20254 financial stock application
 
Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)
 
Scalable Reliable Secure REST
Scalable Reliable Secure RESTScalable Reliable Secure REST
Scalable Reliable Secure REST
 
Decoding real time web communication
Decoding real time web communicationDecoding real time web communication
Decoding real time web communication
 
Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014
 
Http basics by-joshi_29_4_15-ppt
Http basics by-joshi_29_4_15-pptHttp basics by-joshi_29_4_15-ppt
Http basics by-joshi_29_4_15-ppt
 
HTTP
HTTPHTTP
HTTP
 
21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards
 
HTTP
HTTPHTTP
HTTP
 
HTTP fundamentals for developers
HTTP fundamentals for developersHTTP fundamentals for developers
HTTP fundamentals for developers
 
Http protocol
Http protocolHttp protocol
Http protocol
 
Web Performance Hacks
Web Performance HacksWeb Performance Hacks
Web Performance Hacks
 
Server side
Server sideServer side
Server side
 
What's up with HTTP?
What's up with HTTP?What's up with HTTP?
What's up with HTTP?
 
Mashup
MashupMashup
Mashup
 
Web (HTTP) request to response life cycle
Web (HTTP) request to response life cycleWeb (HTTP) request to response life cycle
Web (HTTP) request to response life cycle
 
UOW-Caching and new ways to improve response time (Paper)
UOW-Caching and new ways to improve response time (Paper)UOW-Caching and new ways to improve response time (Paper)
UOW-Caching and new ways to improve response time (Paper)
 
A SURVEY ON WEB PRE-FETCHING AND WEB CACHING TECHNIQUES IN A MOBILE ENVIRONMENT
A SURVEY ON WEB PRE-FETCHING AND WEB CACHING TECHNIQUES IN A MOBILE ENVIRONMENTA SURVEY ON WEB PRE-FETCHING AND WEB CACHING TECHNIQUES IN A MOBILE ENVIRONMENT
A SURVEY ON WEB PRE-FETCHING AND WEB CACHING TECHNIQUES IN A MOBILE ENVIRONMENT
 

Semelhante a Fight empire-html5

Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Masoud Kalali
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketShahriar Hyder
 
21. Application Development and Administration in DBMS
21. Application Development and Administration in DBMS21. Application Development and Administration in DBMS
21. Application Development and Administration in DBMSkoolkampus
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenVannaSchrader3
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxalfredacavx97
 
An In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use Cases
An In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use CasesAn In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use Cases
An In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use CasesTien Nguyen
 
Chat server nitish nagar
Chat server nitish nagarChat server nitish nagar
Chat server nitish nagarNitish Nagar
 
Building Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalRBuilding Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalRShravan Kumar Kasagoni
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt20521742
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 

Semelhante a Fight empire-html5 (20)

Think async
Think asyncThink async
Think async
 
Intro webapps
Intro webappsIntro webapps
Intro webapps
 
ClientServer Websocket.pptx
ClientServer Websocket.pptxClientServer Websocket.pptx
ClientServer Websocket.pptx
 
Web server
Web serverWeb server
Web server
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocket
 
Building real-time-collaborative-web-applications
Building real-time-collaborative-web-applicationsBuilding real-time-collaborative-web-applications
Building real-time-collaborative-web-applications
 
Web servers
Web serversWeb servers
Web servers
 
21. Application Development and Administration in DBMS
21. Application Development and Administration in DBMS21. Application Development and Administration in DBMS
21. Application Development and Administration in DBMS
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
 
Websocket
WebsocketWebsocket
Websocket
 
Web-Socket
Web-SocketWeb-Socket
Web-Socket
 
An In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use Cases
An In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use CasesAn In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use Cases
An In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use Cases
 
Chat server nitish nagar
Chat server nitish nagarChat server nitish nagar
Chat server nitish nagar
 
Building Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalRBuilding Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalR
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 

Mais de Bhakti Mehta

Reliability teamwork
Reliability teamworkReliability teamwork
Reliability teamworkBhakti Mehta
 
Scaling Confluence Architecture: A Sneak Peek Under the Hood
Scaling Confluence Architecture: A Sneak Peek Under the HoodScaling Confluence Architecture: A Sneak Peek Under the Hood
Scaling Confluence Architecture: A Sneak Peek Under the HoodBhakti Mehta
 
Architecting for Failures in micro services: patterns and lessons learned
Architecting for Failures in micro services: patterns and lessons learnedArchitecting for Failures in micro services: patterns and lessons learned
Architecting for Failures in micro services: patterns and lessons learnedBhakti Mehta
 
Let if flow: Java 8 Streams puzzles and more
Let if flow: Java 8 Streams puzzles and moreLet if flow: Java 8 Streams puzzles and more
Let if flow: Java 8 Streams puzzles and moreBhakti Mehta
 
Expect the unexpected: Prepare for failures in microservices
Expect the unexpected: Prepare for failures in microservicesExpect the unexpected: Prepare for failures in microservices
Expect the unexpected: Prepare for failures in microservicesBhakti Mehta
 
Resilience planning and how the empire strikes back
Resilience planning and how the empire strikes backResilience planning and how the empire strikes back
Resilience planning and how the empire strikes backBhakti Mehta
 
Expect the unexpected: Anticipate and prepare for failures in microservices b...
Expect the unexpected: Anticipate and prepare for failures in microservices b...Expect the unexpected: Anticipate and prepare for failures in microservices b...
Expect the unexpected: Anticipate and prepare for failures in microservices b...Bhakti Mehta
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsBhakti Mehta
 
Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhaktiCon fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhaktiBhakti Mehta
 

Mais de Bhakti Mehta (11)

Reliability teamwork
Reliability teamworkReliability teamwork
Reliability teamwork
 
Scaling Confluence Architecture: A Sneak Peek Under the Hood
Scaling Confluence Architecture: A Sneak Peek Under the HoodScaling Confluence Architecture: A Sneak Peek Under the Hood
Scaling Confluence Architecture: A Sneak Peek Under the Hood
 
Devoxx2017
Devoxx2017Devoxx2017
Devoxx2017
 
Architecting for Failures in micro services: patterns and lessons learned
Architecting for Failures in micro services: patterns and lessons learnedArchitecting for Failures in micro services: patterns and lessons learned
Architecting for Failures in micro services: patterns and lessons learned
 
Let if flow: Java 8 Streams puzzles and more
Let if flow: Java 8 Streams puzzles and moreLet if flow: Java 8 Streams puzzles and more
Let if flow: Java 8 Streams puzzles and more
 
Expect the unexpected: Prepare for failures in microservices
Expect the unexpected: Prepare for failures in microservicesExpect the unexpected: Prepare for failures in microservices
Expect the unexpected: Prepare for failures in microservices
 
Resilience planning and how the empire strikes back
Resilience planning and how the empire strikes backResilience planning and how the empire strikes back
Resilience planning and how the empire strikes back
 
Expect the unexpected: Anticipate and prepare for failures in microservices b...
Expect the unexpected: Anticipate and prepare for failures in microservices b...Expect the unexpected: Anticipate and prepare for failures in microservices b...
Expect the unexpected: Anticipate and prepare for failures in microservices b...
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
 
50 tips50minutes
50 tips50minutes50 tips50minutes
50 tips50minutes
 
Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhaktiCon fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhakti
 

Último

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Fight empire-html5

  • 1. Fight the empire light weightly with HTML5, WebSockets, Server-sent Events and others Bhakti Mehta Twitter: @bhakti_mehta
  • 2. Introduction • Currently working as a Senior Software Engineer at Blue Jeans Network. Bluejeans.com • Worked at Sun Microsystems/Oracle for 13 years • Committer to numerous open source projects • Author of Developing RESTful Services with JAX-RS 2.0, WebSockets and JSON Copyright 2013, Bhakti Mehta all rights reserved
  • 3. Fight the empire! Copyright 2013, Bhakti Mehta all rights reserved
  • 4. Agenda  Introduction  Polling  Server- sent Events (SSE)  WebSockets  JAXRS 2.0  JSON-P Copyright 2013, Bhakti Mehta all rights reserved
  • 5. Polling  Used by vast majority of AJAX applications  Poll the server for data  Client --->request--> Server  If no data empty response is returned Copyright 2013, Bhakti Mehta all rights reserved
  • 6. Polling Copyright 2013, Bhakti Mehta all rights reserved Client Server Request (client_id) Response 200 OK: empty Request (client_id) …. …. …. …. Response 200 OK: message body
  • 7. Polling Drawbacks  Http overhead  Reducing the interval will consume more bandwidth and processing resources for nothing. Copyright 2013, Bhakti Mehta all rights reserved
  • 8. Long Polling  If server does not have data holds request open  COMET  Chunked transfer encoding can be used to send chunks of data as part of response body which is opened as a stream.  Chunks can be javascript tags loaded in hidden iframe and executed in order of arrival Copyright 2013, Bhakti Mehta all rights reserved
  • 9. Long Polling Copyright 2013, Bhakti Mehta all rights reserved Client Server Request (client_id) Response 200 OK: message body Request (client_id) …. …. …. Response 200 OK: message body …. ….
  • 10. Long Polling Drawbacks • One-way communication • No standard data format or message format when used in chunked transfer encoding mode • Each connection initiation has the initiation cost. • No caching between clients and server, which impacts the server performance instead of reading some contents from the cache. Copyright 2013, Bhakti Mehta all rights reserved
  • 11. Server-sent events Copyright 2013, Bhakti Mehta all rights reserved  Unidirectional channel between server and client  Server pushes data to your app when it wants  Updates can be streamed from server to client as they happen
  • 12. Server-sent Events Copyright 2013, Bhakti Mehta all rights reserved Client Server Request (client_id) …. …. …. SSE message …. …. SSE message
  • 13. Server-sent Events  Subscribing to event stream To subscribe to an event stream, create an EventSource object and pass it the URL of your stream: Example in javascript eventSource = new EventSource(url); eventSource.onmessage = function (event) { }  Setting up handlers for events You can optionally listen for onopen() and onerror() functions Copyright 2013, Bhakti Mehta all rights reserved
  • 14. Message format for SSE  Sending an event stream  Construct a plaintext response, served with a text/event-stream Content-Type.  Sample message format  data: Help me Obi Wan-Kenobi you are my only hopenn Copyright 2013, Bhakti Mehta all rights reserved
  • 15. Server-sent Events and JSON  Sending JSON You can send multiple lines without breaking JSON format by sending messages like this data: {nn data: "name": Luke Skywalker",nn data: ”home": Tatooinenn data: }nn  On client side source.addEventListener('message', function(e) { var data = JSON.parse(e.data); Copyright 2013, Bhakti Mehta all rights reserved
  • 16. Associating event names with SSE event: order66Issuedn data: {“issuer” : “Chancellor Palpatine”}nn event: jedisPurgedn data: {“survivor” :”Obi-Wan Kenobi, Yoda”}nn Copyright 2013, Bhakti Mehta all rights reserved
  • 17. Associating ids with SSE Associating ids with events can help with fault tolerance in SSE id: 123 n data: Battle of droids deployed at Naboonn Copyright 2013, Bhakti Mehta all rights reserved
  • 18. Connection loss and retries • Browsers that support SSE can try reconnecting to the server in case the connection between browser and server is severed. The default retry interval is 3000 milliseconds but it can be adjusted by including the retry directive in the messages that server sends to the client. • For example to increase the retry interval to 5000 milliseconds SSE message that server sends can be similar to the following listing: retry: 5000n data: This is a single line datann Copyright 2013, Bhakti Mehta all rights reserved
  • 19. Server-sent Events and reconnection  If the connection drops, the EventSource fires an error event and automatically tries to reconnect.  The server can also control the timeout before the client tries to reconnect. Copyright 2013, Bhakti Mehta all rights reserved
  • 20. Best practices for Server- sent Events  Check if eventSource's origin attribute is the expected domain to get the message if (e.origin != 'http://foo.com') { alert('Origin was not http://foo.com'); return; Copyright 2013, Bhakti Mehta all rights reserved
  • 21. Best practices for Server- sent Events  Associating an ID with an event Setting an ID lets the browser keep track of the last event fired  Incase connection is dropped a special Last- Event-ID is set with new request  This lets the browser determine which event is appropriate to fire. The message event contains a e.lastEventId property. Copyright 2013, Bhakti Mehta all rights reserved
  • 22. Comparing Polling vs Long Polling vs SSE  Polling: GET. If data, process data. GET... 1 GET = 1 HTTP response header and maybe a chunk of data.  Long-polling: GET. Wait. Process data. GET... 1 GET = 1 HTTP response header and chunks of data.  SSE: GET. Wait. Process data. Wait. Process data. Wait... 1 GET = 1 HTTP response header and chunks of data with small headers Copyright 2013, Bhakti Mehta all rights reserved
  • 23. WebSockets  Full duplex communication in either direction  Data is framed with 2 bytes  In the case of text frames, each frame starts with a 0x00 byte, ends with a 0xFF byte, and contains UTF-8 data in between. Copyright 2013, Bhakti Mehta all rights reserved
  • 24. WebSockets  Client and Server upgrade from Http protocol to WebSocket protocol during initial handshake GET /text HTTP/1.1rn Upgrade: WebSocketrn Connection: Upgradern Host: www.websocket.orgrn …rn  Handshake from server looks like HTTP/1.1 101 WebSocket Protocol Handshakern Upgrade: WebSocketrn Connection: Upgradern …rn Copyright 2013, Bhakti Mehta all rights reserved
  • 25. WebSockets Handshake Copyright 2013, Bhakti Mehta all rights reserved
  • 26. WebSockets  After the upgrade HTTP is completely out of the picture at this point.  Using the lightweight WebSocket wire protocol, messages can now be sent or received by either endpoint at any time.  Creating a Websocket  ws = new WebSocket("ws://localhost:8080/../WebSocketChat");  You can set handlers for events onopen or onerror Copyright 2013, Bhakti Mehta all rights reserved
  • 27. WebSockets JSR 356  @ServerEndpoint signifies that the Java class it decorates is to be deployed as WebSocket endpoint  Additionally the following components can be annotated with @ServerEndpoint  a stateless session EJB  a singleton EJB  a CDI managed bean Copyright 2013, Bhakti Mehta all rights reserved
  • 28. WebSockets and Security  A web socket which is mapped to a given ws:// URI is protected in the deployment descriptor with a listing to a http:// URI with same hostname, port and path since this is the URL of its opening handshake Copyright 2013, Bhakti Mehta all rights reserved
  • 29. Comparisons Subject SSE WebSockets Long Polling Error Handling Built in support Built in support Almost no error handling in chunked transfer Performance Better than long polling and inferior to WebSockets Best performance Small CPU resource but idle process/thread per client connection limits scalability Communication channel HTTP unidirectional WebSockets bidirectional Http unidirectional Copyright 2013, Bhakti Mehta all rights reserved
  • 30. Comparisons Subject SSE WebSockets Long Polling Implementation complexity Easy Requires websocket support Easiest Browser Support Firefox,Chrome Safari, Opera For RFC 6455: IE 10, Firefox 11, Chrome 16, Safari 6, Opera 12.10 All current browsers Copyright 2013, Bhakti Mehta all rights reserved
  • 31. Best practices for WebSockets • Throttling the rate of sending data • The WebSockets has a bufferedAmount attribute which can be used to control the rate of sending data. Using the bufferedAmount attribute you can check the number of bytes that have been queue but not yet sent to the server. if (webSocket.bufferedAmount < THRESHOLD) webSocket.send(someData); }; Copyright 2013, Bhakti Mehta all rights reserved
  • 32. Best practices for WebSockets • Controlling the maximum size of the message • Use the maxMessageSize attribute on @OnMessage annotation • If the incoming message exceeds the maximum size then the connection is closed. This is a good practice to control the maximum size of a message so that the client does not deplete its resources trying to handle a message, which it can’t process. Copyright 2013, Bhakti Mehta all rights reserved
  • 33. Best practices for WebSockets • Use wss protocol with Proxy servers • Proxy servers may not allow unencrypted Web Socket traffic to flow through. Since the traffic is encrypted there is a greater chance to pass through the proxy server. • Then the CONNECT statements will work and there will be an end-to-end encrypted tunnel for web sockets. Copyright 2013, Bhakti Mehta all rights reserved
  • 34. Best practices for WebSockets Copyright 2013, Bhakti Mehta all rights reserved Client1 Client2 Client3
  • 35. RESTful Webservices • Key principles of REST • Associating IDs to resources • Using standard HTTP methods • Multiple formats data sent by a resource • Statelessness Copyright 2013, Bhakti Mehta all rights reserved
  • 36. RESTful WebServices • GET: The GET request retrieves a representation of a resource from server to client. • POST: The POST request is used to create a resource on the server based on the representation that the client sends. • PUT: The PUT request is used to update or create a reference to a resource on server. • DELETE: The DELETE request can delete a resource on server. • HEAD: The HEAD requests checks for a resource without retrieving it. Copyright 2013, Bhakti Mehta all rights reserved
  • 37. RESTful WebServices • Safety o Invoking a method does not change the resource on server o GET, HEAD are safe o PUT, DELETE, POST are not safe • Idempotence o Calling a method multiple times will not change the result o GET, HEAD, PUT,DELETE are idempotent o POST is not idempotent Copyright 2013, Bhakti Mehta all rights reserved
  • 38. JAX-RS 2.0 Defines how to expose POJOs as web resources, using HTTP as the network protocol. Applications using these APIs can be deployed to an application server in a portable manner. Copyright 2013, Bhakti Mehta all rights reserved
  • 39. Resources and JAX-RS 1.Define a root resource @Path(”jedis") public class JediResource { } 2. Define methods for resource and mime type @GET @Produces(“text/plain”) public String getRank() { return rank; // for eg Youngling, Padawan, Jedi Knight or Jedi Master } Copyright 2013, Bhakti Mehta all rights reserved
  • 40. SubResources and JAX-RS 1.Define a sub resource @Path("/jedis") public class JediResource { @Path(”/jedi/{name}") public Jedi getJedi(@PathParam(”name") String name){ //return Jedi } public class Jedi { @Path(”/apprentice") public String getApprentice(){ } } Copyright 2013, Bhakti Mehta all rights reserved
  • 41. SubResources and JAX-RS • If request is GET /jedis/Yodas • The JediResource.getJedi() method will be invoked. • If a client sends a request using the URI • GET /jedis/Yoda/apprentice • Jedi object is returned and getApprentice() method is invoked Copyright 2013, Bhakti Mehta all rights reserved
  • 42. Client API for JAX-RS 2.0 • Client client = ClientBuilder.newClient(); • WebTarget target = client.target(URI); • String jedi = target.request().get(String.class); Copyright 2013, Bhakti Mehta all rights reserved
  • 43. JAX-RS 2.0  Client API  Filters and Interceptors  Client-side and Server-side Asynchronous  Improved Connection Negotiation  Alignment with JSR 330 Copyright 2013, Bhakti Mehta all rights reserved
  • 44. Java API for JSON Processing JSON-P  Streaming API to produce/consume JSON  Similar to StAX API in XML world  Object model API to represent JSON  Similar to DOM API in XML world Copyright 2013, Bhakti Mehta all rights reserved
  • 45. JsonParser  JsonParser – Parses JSON in a streaming way from input sources  Similar to StAX’s XMLStreamReader, a pull parser  Created  Parser state events : START_ARRAY, START_OBJECT, KEY_NAME, VALUE_STRING, VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, VALUE_NULL, END_OBJECT, END_ARRAY  Created using : Json.createParser(…), Json.createParserFactory().createParser(…) Copyright 2013, Bhakti Mehta all rights reserved
  • 46. JsonGenerator  JsonGenerator – Generates JSON in a streaming way to output sources  Similar to StAX’s XMLStreamWriter  Created using : Json.createGenerator(…), Json.createGeneratorFactory().createGenerator(…) Copyright 2013, Bhakti Mehta all rights reserved
  • 47. JsonReader  Reads JsonObject and JsonArray from input source  Uses pluggable JsonParser try (JsonReader reader = new JsonReader(io)) { JsonObject obj = reader.readObject(); } Copyright 2013, Bhakti Mehta all rights reserved
  • 48. JsonWriter  Writes JsonObject and JsonArray to output source  Uses pluggable JsonGenerator // Writes a JSON object try (JsonWriter writer = new JsonWriter(io)) { writer.writeObject(obj); } Copyright 2013, Bhakti Mehta all rights reserved
  • 49. JSON sample data { ”name": "Jar Jar Binks”, ”home": “Naboo”, ”affilitation": [ { "type": ”primary", "name": ”Royal House of Naboo" }, { "type": ”secondary", "name": ”Galactic republic" }]} ] } Copyright 2013, Bhakti Mehta all rights reserved
  • 50. Call for action • Download GlassFish 4.0 from glassfish.dev.java.net • File issues, contribute patches • Email users@glassfish.dev.java.net Copyright 2013, Bhakti Mehta all rights reserved
  • 51. Questions • Twitter: @bhakti_mehta • Blog https://www.java.net//blogs/bhaktimehta • LinkedIn: http://www.linkedin.com/in/bhaktihmehta • May the force be with you!! Copyright 2013, Bhakti Mehta all rights reserved
  • 52. Copyright 2013, Bhakti Mehta all rights reserved