SlideShare a Scribd company logo
1 of 35
Download to read offline
Getting Started with
WebSocket and Server-Sent
Event in Java
Arun Gupta
Director, Developer Advocacy, Red Hat
blog.arungupta.me, @arungupta

1Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Insert Picture Here
Program
Agenda

 WebSocket Primer
 Getting Started with WebSocket
 Server-Sent Event Primer
 Getting Started with Server-Sent Event
 Resources

2

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Interactive Web Sites
HTTP is half-duplex
HTTP is verbose
Hacks for Server Push
●
Polling
●

Long Polling

●

Comet/Ajax

Complex, Inefficient, Wasteful

3

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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

4

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Establish a connection
Handshake Request

Client

Server
Handshake Response

5

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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

6

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Handshake Response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat

7

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Establishing a Connection
Handshake Request

Client

Server
Handshake Response

Connected !

8

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
WebSocket Lifecycle

Connected !

open

Peer
(client)

open

message
message
message

message
error
message

close

Disconnected
9

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Peer
(server)
WebSocket API
www.w3.org/TR/websockets/

10

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Browser Support

11

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

http://caniuse.com/websockets
12

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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

13

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Annotated Endpoint
import javax.websocket.*;
@ServerEndpoint("/hello")
public class HelloBean {
@OnMessage
public String sayHello(String name) {
return “Hello “ + name;
}
}

14

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Annotations
Annotation

Level

Purpose

@ServerEndpoint

class

Turns a POJO into a WebSocket Endpoint

@ClientEndpoint

class

POJO wants to act as client

@OnMessage
@PathParam

method

Intercepts WebSocket Message events

method
Flags a matched path segment of a URI-template
parameter

@OnOpen

Intercepts WebSocket Open events

@OnClose

method

Intercepts WebSocket Close events

@OnError
15

method

method

Intercepts errors during a conversation

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
@ServerEndpoint Attributes

value
decoders

list of message decoder classnames

encoders

list of message encoder classnames

subprotocols

16

Relative URI or URI template
e.g. “/hello” or “/chat/{subscriber-level}”

list of the names of the supported subprotocols

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Custom Payloads
@ServerEndpoint(
value="/hello",
encoders={MyMessage.class},
decoders={MyMessage.class}
)
public class MyEndpoint {
. . .
}

17

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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();
}
}

18

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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) {
. . .
}
}

19

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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

20

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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);

21

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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);
}
. . .

22

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Chat Server
. . .
@OnMessage
public void message(String message, Session client) {
for (Session peer : peers) {
peer.getBasicRemote().sendObject(message);
}
}
}

23

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
https://blogs.oracle.com/arungupta/entry/collaborative_whiteboard_using_websocket_in

24Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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”);

25

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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) {
}
}
});
}
}

26

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
How to view WebSocket messages ?
Capture traffic on loopback

27

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
How to view WebSocket messages ?
chrome://net-internals -> Sockets -> View live sockets

28

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Server-Sent Events
Part of HTML5 Specification
Server-push notifications
Cross-browser JavaScript API: EventSource
Message callbacks
MIME type: text/eventstream

29

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
EventSource API
dev.w3.org/html5/eventsource/

30

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Server-Sent Events Example
Client-side

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);
}

31

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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;
}

32

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
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());
}

33

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
WebSocket and Server-Sent Event
Competing technologies ?

WebSocket
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

34

Server-Sent Event

Simpler protocol

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
WebSocket and Server-Sent Event
Competing technologies ?

WebSocket
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

35

Server-Sent Event

No support for binary types

Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

More Related Content

What's hot

Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with javaJeongHun Byeon
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentationvlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets PresentationVolodymyr Lavrynovych
 
HTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the WebHTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the WebPeter Lubbers
 
Play + scala + reactive mongo
Play + scala + reactive mongoPlay + scala + reactive mongo
Play + scala + reactive mongoMax Kremer
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkFabio Tiriticco
 
HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5 Server Sent Events/JSF  JAX 2011 ConferenceHTML5 Server Sent Events/JSF  JAX 2011 Conference
HTML5 Server Sent Events/JSF JAX 2011 ConferenceRoger Kitain
 
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
 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIEyal Vardi
 
Service-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMixService-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMixBruce Snyder
 
Jetty Continuation - 이상민
Jetty Continuation - 이상민Jetty Continuation - 이상민
Jetty Continuation - 이상민JavaCommunity.Org
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
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
 

What's hot (19)

Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with java
 
Grizzly 20080925 V2
Grizzly 20080925 V2Grizzly 20080925 V2
Grizzly 20080925 V2
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentationvlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentation
 
HTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the WebHTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the Web
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 
Play + scala + reactive mongo
Play + scala + reactive mongoPlay + scala + reactive mongo
Play + scala + reactive mongo
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
J web socket
J web socketJ web socket
J web socket
 
HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5 Server Sent Events/JSF  JAX 2011 ConferenceHTML5 Server Sent Events/JSF  JAX 2011 Conference
HTML5 Server Sent Events/JSF JAX 2011 Conference
 
Connection Pooling
Connection PoolingConnection Pooling
Connection Pooling
 
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
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
 
Service-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMixService-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMix
 
Jetty Continuation - 이상민
Jetty Continuation - 이상민Jetty Continuation - 이상민
Jetty Continuation - 이상민
 
JAX-RS 2.1 Reloaded @ Devoxx
JAX-RS 2.1 Reloaded @ DevoxxJAX-RS 2.1 Reloaded @ Devoxx
JAX-RS 2.1 Reloaded @ Devoxx
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
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
 

Similar to Getting Started with WebSockets and Server-Sent Events

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
 
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
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_daviddTakashi Ito
 
H2O 3 REST API Overview
H2O 3 REST API OverviewH2O 3 REST API Overview
H2O 3 REST API OverviewRaymond Peck
 
H2O 3 REST API Overview
H2O 3 REST API OverviewH2O 3 REST API Overview
H2O 3 REST API OverviewSri Ambati
 
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
 
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
 
Web Applications Development
Web Applications DevelopmentWeb Applications Development
Web Applications Developmentriround
 
Fight empire-html5
Fight empire-html5Fight empire-html5
Fight empire-html5Bhakti Mehta
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
Get Hip with JHipster - GIDS 2019
Get Hip with JHipster - GIDS 2019Get Hip with JHipster - GIDS 2019
Get Hip with JHipster - GIDS 2019Matt Raible
 
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
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesciklum_ods
 

Similar to Getting Started with WebSockets and Server-Sent Events (20)

WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo ConectadoWebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
 
T2
T2T2
T2
 
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
 
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
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_davidd
 
H2O 3 REST API Overview
H2O 3 REST API OverviewH2O 3 REST API Overview
H2O 3 REST API Overview
 
H2O 3 REST API Overview
H2O 3 REST API OverviewH2O 3 REST API Overview
H2O 3 REST API Overview
 
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)
 
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
 
JAX-RS.next
JAX-RS.nextJAX-RS.next
JAX-RS.next
 
Web Applications Development
Web Applications DevelopmentWeb Applications Development
Web Applications Development
 
Fight empire-html5
Fight empire-html5Fight empire-html5
Fight empire-html5
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Sockets
SocketsSockets
Sockets
 
Get Hip with JHipster - GIDS 2019
Get Hip with JHipster - GIDS 2019Get Hip with JHipster - GIDS 2019
Get Hip with JHipster - GIDS 2019
 
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.
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devices
 
Servlet
ServletServlet
Servlet
 
REST made simple with Java
REST made simple with JavaREST made simple with Java
REST made simple with Java
 
Think async
Think asyncThink async
Think async
 

More from 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
 

More from 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
 

Recently uploaded

CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024Brian Pichman
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInThousandEyes
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfInfopole1
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfTejal81
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxNeo4j
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc
 
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...DianaGray10
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptxHansamali Gamage
 
Scenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenariosScenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenariosErol GIRAUDY
 
March Patch Tuesday
March Patch TuesdayMarch Patch Tuesday
March Patch TuesdayIvanti
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FESTBillieHyde
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNeo4j
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)IES VE
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Muhammad Tiham Siddiqui
 
From the origin to the future of Open Source model and business
From the origin to the future of  Open Source model and businessFrom the origin to the future of  Open Source model and business
From the origin to the future of Open Source model and businessFrancesco Corti
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIVijayananda Mohire
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 

Recently uploaded (20)

CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdf
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
 
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx
 
Scenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenariosScenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenarios
 
March Patch Tuesday
March Patch TuesdayMarch Patch Tuesday
March Patch Tuesday
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FEST
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4j
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)
 
From the origin to the future of Open Source model and business
From the origin to the future of  Open Source model and businessFrom the origin to the future of  Open Source model and business
From the origin to the future of Open Source model and business
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAI
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 

Getting Started with WebSockets and Server-Sent Events

  • 1. Getting Started with WebSocket and Server-Sent Event in Java Arun Gupta Director, Developer Advocacy, Red Hat blog.arungupta.me, @arungupta 1Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Insert Picture Here
  • 2. Program Agenda  WebSocket Primer  Getting Started with WebSocket  Server-Sent Event Primer  Getting Started with Server-Sent Event  Resources 2 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 3. Interactive Web Sites HTTP is half-duplex HTTP is verbose Hacks for Server Push ● Polling ● Long Polling ● Comet/Ajax Complex, Inefficient, Wasteful 3 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 4. 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 4 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 5. Establish a connection Handshake Request Client Server Handshake Response 5 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 6. 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 6 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 7. Handshake Response HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat 7 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 8. Establishing a Connection Handshake Request Client Server Handshake Response Connected ! 8 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 10. WebSocket API www.w3.org/TR/websockets/ 10 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 11. Browser Support 11 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. http://caniuse.com/websockets
  • 12. 12 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 13. 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 13 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 14. Annotated Endpoint import javax.websocket.*; @ServerEndpoint("/hello") public class HelloBean { @OnMessage public String sayHello(String name) { return “Hello “ + name; } } 14 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 15. Annotations Annotation Level Purpose @ServerEndpoint class Turns a POJO into a WebSocket Endpoint @ClientEndpoint class POJO wants to act as client @OnMessage @PathParam method Intercepts WebSocket Message events method Flags a matched path segment of a URI-template parameter @OnOpen Intercepts WebSocket Open events @OnClose method Intercepts WebSocket Close events @OnError 15 method method Intercepts errors during a conversation Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 16. @ServerEndpoint Attributes value decoders list of message decoder classnames encoders list of message encoder classnames subprotocols 16 Relative URI or URI template e.g. “/hello” or “/chat/{subscriber-level}” list of the names of the supported subprotocols Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 17. Custom Payloads @ServerEndpoint( value="/hello", encoders={MyMessage.class}, decoders={MyMessage.class} ) public class MyEndpoint { . . . } 17 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 18. 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(); } } 18 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 19. 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) { . . . } } 19 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 20. 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 20 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 21. 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); 21 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 22. 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); } . . . 22 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 23. Chat Server . . . @OnMessage public void message(String message, Session client) { for (Session peer : peers) { peer.getBasicRemote().sendObject(message); } } } 23 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”); 25 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) { } } }); } } 26 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 27. How to view WebSocket messages ? Capture traffic on loopback 27 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 28. How to view WebSocket messages ? chrome://net-internals -> Sockets -> View live sockets 28 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 29 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 30. EventSource API dev.w3.org/html5/eventsource/ 30 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 31. Server-Sent Events Example Client-side 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); } 31 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; } 32 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()); } 33 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 34. WebSocket and Server-Sent Event Competing technologies ? WebSocket 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 34 Server-Sent Event Simpler protocol Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
  • 35. WebSocket and Server-Sent Event Competing technologies ? WebSocket 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 35 Server-Sent Event No support for binary types Copyright © 2013, Oracle and/or its affiliates. All rights reserved.