SlideShare ist ein Scribd-Unternehmen logo
1 von 39
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 Server/Client Endpoints
–  Annotated (@ServerEndpoint, @ClientEndpoint)
–  Programmatic (Endpoint)
§  WebSocket opening handshake negotiation
§  Lifecycle callback handlers
§  Packaging with Java EE applications
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
https://blogs.oracle.com/arungupta/entry/collaborative_whiteboard_using_websocket_in
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.26
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.27
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.28
How to view WebSocket messages ?
Capture traffic on loopback
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.29
How to view WebSocket messages ?
chrome://net-internals -> Sockets -> View live sockets
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.30
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.31
EventSource API
dev.w3.org/html5/eventsource/
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.32
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.33
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.34
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.35
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.36
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.37
Resources
§  Java API for WebSocket
–  Specification: jcp.org/en/jsr/detail?id=356
–  Reference Implementation: java.net/projects/tyrus
–  Integrated in GlassFish Server 4.0
–  Part of Java EE 7
§  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.38
The preceding material is intended to outline our general product
direction. It is intended for information purposes only, and may not be
incorporated into any contract. It is not a commitment to deliver any
material, code, or functionality, and should not be relied upon in making
purchasing decisions. The development, release, and timing of any
features or functionality described for Oracle’s products remains at the
sole discretion of Oracle.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.39

Weitere ähnliche Inhalte

Was ist angesagt?

Service Oriented Integration With ServiceMix
Service Oriented Integration With ServiceMixService Oriented Integration With ServiceMix
Service Oriented Integration With ServiceMixBruce Snyder
 
Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with javaJeongHun Byeon
 
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
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaJames Falkner
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJoshua Long
 
Java web programming
Java web programmingJava web programming
Java web programmingChing Yi Chan
 
XML and Web Services with Groovy
XML and Web Services with GroovyXML and Web Services with Groovy
XML and Web Services with GroovyPaul King
 
Connecting to Web Services on Android
Connecting to Web Services on AndroidConnecting to Web Services on Android
Connecting to Web Services on Androidsullis
 
Service-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMixService-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMixBruce Snyder
 
ServiceMix 4 -- Integrating OSGi with JBI
ServiceMix 4 -- Integrating OSGi with JBIServiceMix 4 -- Integrating OSGi with JBI
ServiceMix 4 -- Integrating OSGi with JBIGert Vanthienen
 
An Introduction to Apache ServiceMix 4 - FUSE ESB
An Introduction to Apache ServiceMix 4 - FUSE ESBAn Introduction to Apache ServiceMix 4 - FUSE ESB
An Introduction to Apache ServiceMix 4 - FUSE ESBAdrian Trenaman
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketV2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketbrent bucci
 
Android webservices
Android webservicesAndroid webservices
Android webservicesKrazy Koder
 

Was ist angesagt? (19)

WebSockets in JEE 7
WebSockets in JEE 7WebSockets in JEE 7
WebSockets in JEE 7
 
Service Oriented Integration With ServiceMix
Service Oriented Integration With ServiceMixService Oriented Integration With ServiceMix
Service Oriented Integration With ServiceMix
 
Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with java
 
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
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
Grizzly 20080925 V2
Grizzly 20080925 V2Grizzly 20080925 V2
Grizzly 20080925 V2
 
HTML5 WebSockets
HTML5 WebSocketsHTML5 WebSockets
HTML5 WebSockets
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
Java web programming
Java web programmingJava web programming
Java web programming
 
XML and Web Services with Groovy
XML and Web Services with GroovyXML and Web Services with Groovy
XML and Web Services with Groovy
 
J web socket
J web socketJ web socket
J web socket
 
Connecting to Web Services on Android
Connecting to Web Services on AndroidConnecting to Web Services on Android
Connecting to Web Services on Android
 
Service-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMixService-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMix
 
ServiceMix 4 -- Integrating OSGi with JBI
ServiceMix 4 -- Integrating OSGi with JBIServiceMix 4 -- Integrating OSGi with JBI
ServiceMix 4 -- Integrating OSGi with JBI
 
An Introduction to Apache ServiceMix 4 - FUSE ESB
An Introduction to Apache ServiceMix 4 - FUSE ESBAn Introduction to Apache ServiceMix 4 - FUSE ESB
An Introduction to Apache ServiceMix 4 - FUSE ESB
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketV2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocket
 
Android webservices
Android webservicesAndroid webservices
Android webservices
 

Ähnlich wie Getting Started with WebSocket and Server-Sent Events in Java

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
 
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
 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo ConectadoWebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo ConectadoBruno Borges
 
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
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesJAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesArun Gupta
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_daviddTakashi Ito
 
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
 
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
 
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
 
Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Arun Gupta
 
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...jaxLondonConference
 
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
 
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
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX LondonJAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX LondonArun Gupta
 
JavaOne Shanghai 2013 - Servlet 3.1 (JSR 340)
JavaOne Shanghai 2013 - Servlet 3.1 (JSR 340)JavaOne Shanghai 2013 - Servlet 3.1 (JSR 340)
JavaOne Shanghai 2013 - Servlet 3.1 (JSR 340)Shing Wai Chan
 
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
 

Ähnlich wie Getting Started with WebSocket and Server-Sent Events in Java (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...
 
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
 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo ConectadoWebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
 
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
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesJAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web Services
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_davidd
 
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
 
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)
 
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
 
Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5
 
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
 
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.
 
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.
 
Java ee7 1hour
Java ee7 1hourJava ee7 1hour
Java ee7 1hour
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX LondonJAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
 
JavaOne Shanghai 2013 - Servlet 3.1 (JSR 340)
JavaOne Shanghai 2013 - Servlet 3.1 (JSR 340)JavaOne Shanghai 2013 - Servlet 3.1 (JSR 340)
JavaOne Shanghai 2013 - Servlet 3.1 (JSR 340)
 
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
 
Java Cloud and Container Ready
Java Cloud and Container ReadyJava Cloud and Container Ready
Java Cloud and Container Ready
 

Mehr von Arun Gupta

5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdfArun Gupta
 
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Arun Gupta
 
Machine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesMachine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesArun Gupta
 
Secure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerSecure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerArun Gupta
 
Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Arun Gupta
 
Why Amazon Cares about Open Source
Why Amazon Cares about Open SourceWhy Amazon Cares about Open Source
Why Amazon Cares about Open SourceArun Gupta
 
Machine learning using Kubernetes
Machine learning using KubernetesMachine learning using Kubernetes
Machine learning using KubernetesArun Gupta
 
Building Cloud Native Applications
Building Cloud Native ApplicationsBuilding Cloud Native Applications
Building Cloud Native ApplicationsArun Gupta
 
Chaos Engineering with Kubernetes
Chaos Engineering with KubernetesChaos Engineering with Kubernetes
Chaos Engineering with KubernetesArun Gupta
 
How to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMHow to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMArun Gupta
 
Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Arun Gupta
 
The Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteThe Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteArun Gupta
 
Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Arun Gupta
 
Mastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitMastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitArun Gupta
 
Top 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeTop 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeArun Gupta
 
Container Landscape in 2017
Container Landscape in 2017Container Landscape in 2017
Container Landscape in 2017Arun Gupta
 
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftJava EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftArun Gupta
 
Docker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersDocker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersArun Gupta
 
Thanks Managers!
Thanks Managers!Thanks Managers!
Thanks Managers!Arun Gupta
 
Migrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersMigrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersArun Gupta
 

Mehr von Arun Gupta (20)

5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf
 
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019
 
Machine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesMachine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and Kubernetes
 
Secure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerSecure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using Firecracker
 
Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019
 
Why Amazon Cares about Open Source
Why Amazon Cares about Open SourceWhy Amazon Cares about Open Source
Why Amazon Cares about Open Source
 
Machine learning using Kubernetes
Machine learning using KubernetesMachine learning using Kubernetes
Machine learning using Kubernetes
 
Building Cloud Native Applications
Building Cloud Native ApplicationsBuilding Cloud Native Applications
Building Cloud Native Applications
 
Chaos Engineering with Kubernetes
Chaos Engineering with KubernetesChaos Engineering with Kubernetes
Chaos Engineering with Kubernetes
 
How to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMHow to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAM
 
Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018
 
The Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteThe Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 Keynote
 
Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018
 
Mastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitMastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv Summit
 
Top 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeTop 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's Landscape
 
Container Landscape in 2017
Container Landscape in 2017Container Landscape in 2017
Container Landscape in 2017
 
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftJava EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShift
 
Docker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersDocker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developers
 
Thanks Managers!
Thanks Managers!Thanks Managers!
Thanks Managers!
 
Migrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersMigrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to Containers
 

Kürzlich hochgeladen

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Kürzlich hochgeladen (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

Getting Started with WebSocket and Server-Sent Events in Java

  • 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 Server/Client Endpoints –  Annotated (@ServerEndpoint, @ClientEndpoint) –  Programmatic (Endpoint) §  WebSocket opening handshake negotiation §  Lifecycle callback handlers §  Packaging with Java EE applications
  • 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 https://blogs.oracle.com/arungupta/entry/collaborative_whiteboard_using_websocket_in
  • 26. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.26 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”);" "
  • 27. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.27 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) {
 }
 } 
 });
 }
 }"
  • 28. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.28 How to view WebSocket messages ? Capture traffic on loopback
  • 29. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.29 How to view WebSocket messages ? chrome://net-internals -> Sockets -> View live sockets
  • 30. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.30 Server-Sent Events §  Part of HTML5 Specification §  Server-push notifications §  Cross-browser JavaScript API: EventSource" §  Message callbacks §  MIME type: text/eventstream"
  • 31. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.31 EventSource API dev.w3.org/html5/eventsource/
  • 32. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.32 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
  • 33. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.33 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;
 }
  • 34. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.34 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());
 }
  • 35. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.35 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
  • 36. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.36 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
  • 37. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.37 Resources §  Java API for WebSocket –  Specification: jcp.org/en/jsr/detail?id=356 –  Reference Implementation: java.net/projects/tyrus –  Integrated in GlassFish Server 4.0 –  Part of Java EE 7 §  Server-Sent Event –  Integrated in Jersey and GlassFish Server 4.0 –  Not part of Java EE 7
  • 38. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.38 The preceding material is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
  • 39. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.39