SlideShare una empresa de Scribd logo
1 de 37
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.1
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.2
Getting Started with
WebSocket and Server-Sent
Event in Java
Arun Gupta
blogs.oracle.com/arungupta, @arungupta
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.3 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 16
Program
Agenda
§  WebSocket Primer
§  Getting Started with WebSocket
§  Server-Sent Event Primer
§  Getting Started with Server-Sent Event
§  Resources
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.4
Interactive Web Sites
§  HTTP is half-duplex
§  HTTP is verbose
§  Hacks for Server Push
–  Polling
–  Long Polling
–  Comet/Ajax
§  Complex, Inefficient, Wasteful
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.5
WebSocket to the Rescue
§  TCP based, bi-directional, full-duplex messaging
§  Originally proposed as part of HTML5
§  IETF-defined Protocol: RFC 6455
–  Handshake
–  Data Transfer
§  W3C defined JavaScript API
–  Candidate Recommendation
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.6
Establish a connection
Client
Handshake Request
Handshake Response
Server
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.7
Handshake Request
GET /chat HTTP/1.1

Host: server.example.com

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==

Origin: http://example.com

Sec-WebSocket-Protocol: chat, superchat

Sec-WebSocket-Version: 13 "
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.8
Handshake Response
HTTP/1.1 101 Switching Protocols

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Sec-WebSocket-Protocol: chat "
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.9
ServerClient
Handshake Request
Handshake Response
Connected !
Establishing a Connection
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.10
Peer
(server)
Peer
(client)
Connected !
open open
close
message
error
message
message
message
message
Disconnected
WebSocket Lifecycle
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.11
WebSocket API
www.w3.org/TR/websockets/
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.12 http://caniuse.com/websockets
Browser Support
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.13
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.14
Java API for WebSocket Features
§  API for WebSocket Endpoints/Client
–  Annotation-driven (@ServerEndpoint)
–  Interface-driven (Endpoint)
§  WebSocket opening handshake negotiation
–  Client (@ClientEndpoint)
§  Integration with Java EE Web container
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.15
Annotated Endpoint
import javax.websocket.*;



@ServerEndpoint("/hello")

public class HelloBean {



@OnMessage

public String sayHello(String name) {

return “Hello “ + name;

}

}"
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.16
Annotations
Annotation Level Purpose
@ServerEndpoint" class Turns a POJO into a WebSocket Endpoint
@ClientEndpoint" class POJO wants to act as client
@OnMessage" method Intercepts WebSocket Message events
@PathParam"
method
parameter
Flags a matched path segment of a URI-template
@OnOpen" method Intercepts WebSocket Open events
@OnClose" method Intercepts WebSocket Close events
@OnError" method Intercepts errors during a conversation
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.17
@ServerEndpoint Attributes
value"
Relative URI or URI template
e.g. /hello or /chat/{subscriber-level}
decoders" list of message decoder classnames
encoders" list of message encoder classnames
subprotocols" list of the names of the supported subprotocols
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.18
Custom Payloads
@ServerEndpoint(

value="/hello",

encoders={MyMessage.class},

decoders={MyMessage.class}

)

public class MyEndpoint {

. . .

}"
"
"
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.19
Custom Payloads – Text
public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> {

private JsonObject jsonObject;



public MyMessage decode(String s) {

jsonObject = Json.createReader(new StringReader(s)).readObject();

return this;"
}"
public boolean willDecode(String string) {

return true; // Only if can process the payload

}"
"
public String encode(MyMessage myMessage) {

return myMessage.jsonObject.toString();

}

}"
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.20
Custom Payloads – Binary
public class MyMessage implements Decoder.Binary<MyMessage>, Encoder.Binary<MyMessage> {



public MyMessage decode(byte[] bytes) {

. . .

return this;"
}"
public boolean willDecode(byte[] bytes) {

. . .

return true; // Only if can process the payload

}"
"
public byte[] encode(MyMessage myMessage) {

. . .

}

}"
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.21
Which methods can be @OnMessage ?
§  Exactly one of the following
–  Text: String, Java primitive or equivalent class, String and boolean,
Reader, any type for which there is a decoder
–  Binary: byte[], ByteBuffer, byte[] and boolean, ByteBuffer and
boolean, InptuStream, any type for which there is a decoder
–  Pong messages: PongMessage"
§  An optional Session parameter
§  0..n String parameters annotated with @PathParam"
§  Return type: String, byte[], ByteBuffer, Java primitive or class
equivalent or any type for which there is a encoder
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.22
Sample Messages
§  void m(String s);"
§  void m(Float f, @PathParam(“id”)int id);"
§  Product m(Reader reader, Session s);"
§  void m(byte[] b); or void m(ByteBuffer b);"
§  Book m(int i, Session s, @PathParam(“isbn”)String
isbn, @PathParam(“store”)String store);"
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.23
Chat Server
@ServerEndpoint("/chat")"
public class ChatBean {"
static Set<Session> peers = Collections.synchronizedSet(…);



@OnOpen

public void onOpen(Session peer) {

peers.add(peer);

}



@OnClose

public void onClose(Session peer) {

peers.remove(peer);

}



. . ."
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.24
Chat Server
. . .



@OnMessage"
public void message(String message, Session client) {"
for (Session peer : peers) {

peer.getBasicRemote().sendObject(message);

}

}

}"
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.25
WebSocket Client
@ClientEndpoint

public class HelloClient {

@OnMessage

public void message(String message, Session session) {

// process message from server

}

}

"
WebSocketContainer c = ContainerProvider.getWebSocketContainer();

c.connectToServer(HelloClient.class, “hello”);"
"
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.26
Programmatic Endpoint
public class MyEndpoint extends Endpoint {



@Override

public void onOpen(Session session) {

session.addMessageHandler(new MessageHandler.Text() {

public void onMessage(String name) {

try {

session.getBasicRemote().sendText(“Hello “ + name);

} catch (IOException ex) {

}

} 

});

}

}"
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.27
How to view WebSocket messages ?
Capture traffic on loopback
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.28
How to view WebSocket messages ?
chrome://net-internals -> Sockets -> View live sockets
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.29
Server-Sent Events
§  Part of HTML5 Specification
§  Server-push notifications
§  Cross-browser JavaScript API: EventSource"
§  Message callbacks
§  MIME type: text/eventstream"
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.30
EventSource API
dev.w3.org/html5/eventsource/
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.31
Server-Sent Events Example
var url = ‘webresources/items/events’;

var source = new EventSource(url);"
source.onmessage = function (event) {

console.log(event.data);

}

source.addEventListener(“size”, function(event) {"
console.log(event.name + ‘ ‘ + event.data);

}"
Client-side
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.32
Server-Sent Events Example
private final SseBroadcaster BROADCASTER = new SseBroadcaster();



@GET

@Path("events”)

@Produces(SseFeature.SERVER_SENT_EVENTS)

public EventOutput fruitEvents() {

final EventOutput eventOutput = new EventOutput();

BROADCASTER.add(eventOutput);

return eventOutput;

}
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.33
Server-Sent Events Example
@POST

@Consumes(MediaType.APPLICATION_FORM_URLENCODED)

public void addFruit(@FormParam("fruit")String fruit) {

FRUITS.add(fruit);



// Broadcasting an un-named event with the name of the newly added item in data

BROADCASTER.broadcast(new OutboundEvent.Builder().data(String.class, fruit).build());



// Broadcasting a named "add" event with the current size of the items collection in
data

BROADCASTER.broadcast(new OutboundEvent.Builder().name("size").data(Integer.class,
FRUITS.size()).build());

}
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.34
WebSocket and Server-Sent Event
Competing technologies ?
WebSocket Server-Sent Event
Over a custom protocol Over simple HTTP
Full Duplex, Bi-directional Server-Push Only, Client->Server
is out-of-band (higher latency)
Native support in most browsers Can be poly-filled to backport
Not straight forward protocol Simpler protocol
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.35
WebSocket and Server-Sent Event
Competing technologies ?
WebSocket Server-Sent Event
Pre-defined message handlers Arbitrary events
Application-specific Built-in support for re-connection
and event id
Require server and/or proxy
configurations
No server or proxy changes
required
ArrayBuffer and Blob No support for binary types
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.36
Resources
§  Java API for WebSocket
–  Specification: jcp.org/en/jsr/detail?id=356
–  Reference Implementation: java.net/projects/tyrus
–  Part of Java EE 7
–  Integrated in GlassFish Server 4.0
§  Server-Sent Event
–  Integrated in Jersey and GlassFish Server 4.0
–  Not part of Java EE 7
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.37

Más contenido relacionado

La actualidad más candente

RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSCarol McDonald
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSRestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSNeil Ghosh
 
Java EE and Spring Side-by-Side
Java EE and Spring Side-by-SideJava EE and Spring Side-by-Side
Java EE and Spring Side-by-SideReza Rahman
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEREST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEreneechemel
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2Geoffrey Fox
 
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
 
Rest Security with JAX-RS
Rest Security with JAX-RSRest Security with JAX-RS
Rest Security with JAX-RSFrank Kim
 
Writing & Using Web Services
Writing & Using Web ServicesWriting & Using Web Services
Writing & Using Web ServicesRajarshi Guha
 
RESTful Web Services with Spring MVC
RESTful Web Services with Spring MVCRESTful Web Services with Spring MVC
RESTful Web Services with Spring MVCdigitalsonic
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RSArun Gupta
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WSKatrien Verbert
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLHTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLUlf Wendel
 

La actualidad más candente (17)

RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSRestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Java EE and Spring Side-by-Side
Java EE and Spring Side-by-SideJava EE and Spring Side-by-Side
Java EE and Spring Side-by-Side
 
Think async
Think asyncThink async
Think async
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEREST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2
 
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
 
Rest Security with JAX-RS
Rest Security with JAX-RSRest Security with JAX-RS
Rest Security with JAX-RS
 
OAuth: Trust Issues
OAuth: Trust IssuesOAuth: Trust Issues
OAuth: Trust Issues
 
Writing & Using Web Services
Writing & Using Web ServicesWriting & Using Web Services
Writing & Using Web Services
 
RESTful Web Services with Spring MVC
RESTful Web Services with Spring MVCRESTful Web Services with Spring MVC
RESTful Web Services with Spring MVC
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RS
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLHTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
 

Destacado

Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long jaxconf
 
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin HerbasThe New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbasjaxconf
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remanijaxconf
 
What you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie AllenWhat you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie Allenjaxconf
 
Future of the Web - Yehuda Katz
Future of the Web - Yehuda KatzFuture of the Web - Yehuda Katz
Future of the Web - Yehuda Katzjaxconf
 
The Spring 4 Update - Josh Long
The Spring 4 Update - Josh LongThe Spring 4 Update - Josh Long
The Spring 4 Update - Josh Longjaxconf
 
Building an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen TingBuilding an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen Tingjaxconf
 
Java PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao KandJava PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao Kandjaxconf
 
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu BariApache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu Barijaxconf
 
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...jaxconf
 
JSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian HlavatsJSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian Hlavatsjaxconf
 
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...jaxconf
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargentajaxconf
 
The Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun SmithThe Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun Smithjaxconf
 
From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEjaxconf
 
EarthLink Business Hosted Exchange Solution
EarthLink Business Hosted Exchange SolutionEarthLink Business Hosted Exchange Solution
EarthLink Business Hosted Exchange SolutionMike Ricca
 
Tugas akhir tik angga susila putra & syarif hidayatullah xii ipa 2
Tugas akhir tik angga susila putra & syarif hidayatullah xii ipa 2Tugas akhir tik angga susila putra & syarif hidayatullah xii ipa 2
Tugas akhir tik angga susila putra & syarif hidayatullah xii ipa 2Paarief Udin
 
Vuelo de gansos
Vuelo de gansosVuelo de gansos
Vuelo de gansosEdnaLiceth
 

Destacado (18)

Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin HerbasThe New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remani
 
What you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie AllenWhat you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie Allen
 
Future of the Web - Yehuda Katz
Future of the Web - Yehuda KatzFuture of the Web - Yehuda Katz
Future of the Web - Yehuda Katz
 
The Spring 4 Update - Josh Long
The Spring 4 Update - Josh LongThe Spring 4 Update - Josh Long
The Spring 4 Update - Josh Long
 
Building an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen TingBuilding an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen Ting
 
Java PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao KandJava PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao Kand
 
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu BariApache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
 
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
 
JSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian HlavatsJSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian Hlavats
 
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargenta
 
The Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun SmithThe Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun Smith
 
From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEE
 
EarthLink Business Hosted Exchange Solution
EarthLink Business Hosted Exchange SolutionEarthLink Business Hosted Exchange Solution
EarthLink Business Hosted Exchange Solution
 
Tugas akhir tik angga susila putra & syarif hidayatullah xii ipa 2
Tugas akhir tik angga susila putra & syarif hidayatullah xii ipa 2Tugas akhir tik angga susila putra & syarif hidayatullah xii ipa 2
Tugas akhir tik angga susila putra & syarif hidayatullah xii ipa 2
 
Vuelo de gansos
Vuelo de gansosVuelo de gansos
Vuelo de gansos
 

Similar a Getting started with Websocket and Server-sent Events using Java - Arun Gupta

Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...jaxLondonConference
 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo ConectadoWebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo ConectadoBruno Borges
 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFishJava API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFishArun Gupta
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureFrank Greco
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_daviddTakashi Ito
 
JAX RS 2.0 - OTN Bangalore 2013
JAX RS 2.0 - OTN Bangalore 2013JAX RS 2.0 - OTN Bangalore 2013
JAX RS 2.0 - OTN Bangalore 2013Jagadish Prasath
 
OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7Bruno Borges
 
Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.Edward Burns
 
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014David Delabassee
 
MySQL Proxy. A powerful, flexible MySQL toolbox.
MySQL Proxy. A powerful, flexible MySQL toolbox.MySQL Proxy. A powerful, flexible MySQL toolbox.
MySQL Proxy. A powerful, flexible MySQL toolbox.Miguel Araújo
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersViktor Gamov
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG  - March 2014)Java EE 7 (Lyon JUG & Alpes JUG  - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)David Delabassee
 
Kick Start your Application Development and Management Strategy
Kick Start your Application Development and Management Strategy Kick Start your Application Development and Management Strategy
Kick Start your Application Development and Management Strategy WSO2
 
Understanding and Developing Web Services: For DBAs and Database Developers
Understanding and Developing Web Services: For DBAs and Database DevelopersUnderstanding and Developing Web Services: For DBAs and Database Developers
Understanding and Developing Web Services: For DBAs and Database DevelopersRevelation Technologies
 
EWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD MessagesEWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD MessagesRob Tweed
 
Java EE 7 in practise - OTN Hyderabad 2014
Java EE 7 in practise - OTN Hyderabad 2014Java EE 7 in practise - OTN Hyderabad 2014
Java EE 7 in practise - OTN Hyderabad 2014Jagadish Prasath
 
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)Shing Wai Chan
 
Automating Cloud Operations - Everything you wanted to know about cURL and RE...
Automating Cloud Operations - Everything you wanted to know about cURL and RE...Automating Cloud Operations - Everything you wanted to know about cURL and RE...
Automating Cloud Operations - Everything you wanted to know about cURL and RE...Revelation Technologies
 

Similar a Getting started with Websocket and Server-sent Events using Java - Arun Gupta (20)

Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo ConectadoWebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFishJava API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFish
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the Future
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_davidd
 
JAX RS 2.0 - OTN Bangalore 2013
JAX RS 2.0 - OTN Bangalore 2013JAX RS 2.0 - OTN Bangalore 2013
JAX RS 2.0 - OTN Bangalore 2013
 
OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7
 
Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.
 
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
 
MySQL Proxy. A powerful, flexible MySQL toolbox.
MySQL Proxy. A powerful, flexible MySQL toolbox.MySQL Proxy. A powerful, flexible MySQL toolbox.
MySQL Proxy. A powerful, flexible MySQL toolbox.
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
 
Java ee7 1hour
Java ee7 1hourJava ee7 1hour
Java ee7 1hour
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG  - March 2014)Java EE 7 (Lyon JUG & Alpes JUG  - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
 
Kick Start your Application Development and Management Strategy
Kick Start your Application Development and Management Strategy Kick Start your Application Development and Management Strategy
Kick Start your Application Development and Management Strategy
 
Understanding and Developing Web Services: For DBAs and Database Developers
Understanding and Developing Web Services: For DBAs and Database DevelopersUnderstanding and Developing Web Services: For DBAs and Database Developers
Understanding and Developing Web Services: For DBAs and Database Developers
 
EWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD MessagesEWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD Messages
 
Java EE 7 in practise - OTN Hyderabad 2014
Java EE 7 in practise - OTN Hyderabad 2014Java EE 7 in practise - OTN Hyderabad 2014
Java EE 7 in practise - OTN Hyderabad 2014
 
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
 
Automating Cloud Operations - Everything you wanted to know about cURL and RE...
Automating Cloud Operations - Everything you wanted to know about cURL and RE...Automating Cloud Operations - Everything you wanted to know about cURL and RE...
Automating Cloud Operations - Everything you wanted to know about cURL and RE...
 

Último

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 

Último (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 

Getting started with Websocket and Server-sent Events using Java - Arun Gupta

  • 1. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.1
  • 2. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.2 Getting Started with WebSocket and Server-Sent Event in Java Arun Gupta blogs.oracle.com/arungupta, @arungupta
  • 3. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.3 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 16 Program Agenda §  WebSocket Primer §  Getting Started with WebSocket §  Server-Sent Event Primer §  Getting Started with Server-Sent Event §  Resources
  • 4. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.4 Interactive Web Sites §  HTTP is half-duplex §  HTTP is verbose §  Hacks for Server Push –  Polling –  Long Polling –  Comet/Ajax §  Complex, Inefficient, Wasteful
  • 5. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.5 WebSocket to the Rescue §  TCP based, bi-directional, full-duplex messaging §  Originally proposed as part of HTML5 §  IETF-defined Protocol: RFC 6455 –  Handshake –  Data Transfer §  W3C defined JavaScript API –  Candidate Recommendation
  • 6. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.6 Establish a connection Client Handshake Request Handshake Response Server
  • 7. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.7 Handshake Request GET /chat HTTP/1.1
 Host: server.example.com
 Upgrade: websocket
 Connection: Upgrade
 Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
 Origin: http://example.com
 Sec-WebSocket-Protocol: chat, superchat
 Sec-WebSocket-Version: 13 "
  • 8. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.8 Handshake Response HTTP/1.1 101 Switching Protocols
 Upgrade: websocket
 Connection: Upgrade
 Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 Sec-WebSocket-Protocol: chat "
  • 9. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.9 ServerClient Handshake Request Handshake Response Connected ! Establishing a Connection
  • 10. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.10 Peer (server) Peer (client) Connected ! open open close message error message message message message Disconnected WebSocket Lifecycle
  • 11. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.11 WebSocket API www.w3.org/TR/websockets/
  • 12. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.12 http://caniuse.com/websockets Browser Support
  • 13. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.13
  • 14. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.14 Java API for WebSocket Features §  API for WebSocket Endpoints/Client –  Annotation-driven (@ServerEndpoint) –  Interface-driven (Endpoint) §  WebSocket opening handshake negotiation –  Client (@ClientEndpoint) §  Integration with Java EE Web container
  • 15. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.15 Annotated Endpoint import javax.websocket.*;
 
 @ServerEndpoint("/hello")
 public class HelloBean {
 
 @OnMessage
 public String sayHello(String name) {
 return “Hello “ + name;
 }
 }"
  • 16. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.16 Annotations Annotation Level Purpose @ServerEndpoint" class Turns a POJO into a WebSocket Endpoint @ClientEndpoint" class POJO wants to act as client @OnMessage" method Intercepts WebSocket Message events @PathParam" method parameter Flags a matched path segment of a URI-template @OnOpen" method Intercepts WebSocket Open events @OnClose" method Intercepts WebSocket Close events @OnError" method Intercepts errors during a conversation
  • 17. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.17 @ServerEndpoint Attributes value" Relative URI or URI template e.g. /hello or /chat/{subscriber-level} decoders" list of message decoder classnames encoders" list of message encoder classnames subprotocols" list of the names of the supported subprotocols
  • 18. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.18 Custom Payloads @ServerEndpoint(
 value="/hello",
 encoders={MyMessage.class},
 decoders={MyMessage.class}
 )
 public class MyEndpoint {
 . . .
 }" " "
  • 19. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.19 Custom Payloads – Text public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> {
 private JsonObject jsonObject;
 
 public MyMessage decode(String s) {
 jsonObject = Json.createReader(new StringReader(s)).readObject();
 return this;" }" public boolean willDecode(String string) {
 return true; // Only if can process the payload
 }" " public String encode(MyMessage myMessage) {
 return myMessage.jsonObject.toString();
 }
 }"
  • 20. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.20 Custom Payloads – Binary public class MyMessage implements Decoder.Binary<MyMessage>, Encoder.Binary<MyMessage> {
 
 public MyMessage decode(byte[] bytes) {
 . . .
 return this;" }" public boolean willDecode(byte[] bytes) {
 . . .
 return true; // Only if can process the payload
 }" " public byte[] encode(MyMessage myMessage) {
 . . .
 }
 }"
  • 21. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.21 Which methods can be @OnMessage ? §  Exactly one of the following –  Text: String, Java primitive or equivalent class, String and boolean, Reader, any type for which there is a decoder –  Binary: byte[], ByteBuffer, byte[] and boolean, ByteBuffer and boolean, InptuStream, any type for which there is a decoder –  Pong messages: PongMessage" §  An optional Session parameter §  0..n String parameters annotated with @PathParam" §  Return type: String, byte[], ByteBuffer, Java primitive or class equivalent or any type for which there is a encoder
  • 22. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.22 Sample Messages §  void m(String s);" §  void m(Float f, @PathParam(“id”)int id);" §  Product m(Reader reader, Session s);" §  void m(byte[] b); or void m(ByteBuffer b);" §  Book m(int i, Session s, @PathParam(“isbn”)String isbn, @PathParam(“store”)String store);"
  • 23. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.23 Chat Server @ServerEndpoint("/chat")" public class ChatBean {" static Set<Session> peers = Collections.synchronizedSet(…);
 
 @OnOpen
 public void onOpen(Session peer) {
 peers.add(peer);
 }
 
 @OnClose
 public void onClose(Session peer) {
 peers.remove(peer);
 }
 
 . . ."
  • 24. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.24 Chat Server . . .
 
 @OnMessage" public void message(String message, Session client) {" for (Session peer : peers) {
 peer.getBasicRemote().sendObject(message);
 }
 }
 }"
  • 25. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.25 WebSocket Client @ClientEndpoint
 public class HelloClient {
 @OnMessage
 public void message(String message, Session session) {
 // process message from server
 }
 }
 " WebSocketContainer c = ContainerProvider.getWebSocketContainer();
 c.connectToServer(HelloClient.class, “hello”);" "
  • 26. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.26 Programmatic Endpoint public class MyEndpoint extends Endpoint {
 
 @Override
 public void onOpen(Session session) {
 session.addMessageHandler(new MessageHandler.Text() {
 public void onMessage(String name) {
 try {
 session.getBasicRemote().sendText(“Hello “ + name);
 } catch (IOException ex) {
 }
 } 
 });
 }
 }"
  • 27. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.27 How to view WebSocket messages ? Capture traffic on loopback
  • 28. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.28 How to view WebSocket messages ? chrome://net-internals -> Sockets -> View live sockets
  • 29. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.29 Server-Sent Events §  Part of HTML5 Specification §  Server-push notifications §  Cross-browser JavaScript API: EventSource" §  Message callbacks §  MIME type: text/eventstream"
  • 30. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.30 EventSource API dev.w3.org/html5/eventsource/
  • 31. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.31 Server-Sent Events Example var url = ‘webresources/items/events’;
 var source = new EventSource(url);" source.onmessage = function (event) {
 console.log(event.data);
 }
 source.addEventListener(“size”, function(event) {" console.log(event.name + ‘ ‘ + event.data);
 }" Client-side
  • 32. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.32 Server-Sent Events Example private final SseBroadcaster BROADCASTER = new SseBroadcaster();
 
 @GET
 @Path("events”)
 @Produces(SseFeature.SERVER_SENT_EVENTS)
 public EventOutput fruitEvents() {
 final EventOutput eventOutput = new EventOutput();
 BROADCASTER.add(eventOutput);
 return eventOutput;
 }
  • 33. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.33 Server-Sent Events Example @POST
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 public void addFruit(@FormParam("fruit")String fruit) {
 FRUITS.add(fruit);
 
 // Broadcasting an un-named event with the name of the newly added item in data
 BROADCASTER.broadcast(new OutboundEvent.Builder().data(String.class, fruit).build());
 
 // Broadcasting a named "add" event with the current size of the items collection in data
 BROADCASTER.broadcast(new OutboundEvent.Builder().name("size").data(Integer.class, FRUITS.size()).build());
 }
  • 34. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.34 WebSocket and Server-Sent Event Competing technologies ? WebSocket Server-Sent Event Over a custom protocol Over simple HTTP Full Duplex, Bi-directional Server-Push Only, Client->Server is out-of-band (higher latency) Native support in most browsers Can be poly-filled to backport Not straight forward protocol Simpler protocol
  • 35. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.35 WebSocket and Server-Sent Event Competing technologies ? WebSocket Server-Sent Event Pre-defined message handlers Arbitrary events Application-specific Built-in support for re-connection and event id Require server and/or proxy configurations No server or proxy changes required ArrayBuffer and Blob No support for binary types
  • 36. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.36 Resources §  Java API for WebSocket –  Specification: jcp.org/en/jsr/detail?id=356 –  Reference Implementation: java.net/projects/tyrus –  Part of Java EE 7 –  Integrated in GlassFish Server 4.0 §  Server-Sent Event –  Integrated in Jersey and GlassFish Server 4.0 –  Not part of Java EE 7
  • 37. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.37