SlideShare a Scribd company logo
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.
Ad

Recommended

Server-Side Programming Primer
Server-Side Programming Primer
Ivano Malavolta
ย 
HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5 Server Sent Events/JSF JAX 2011 Conference
Roger Kitain
ย 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
Arun Gupta
ย 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Masoud Kalali
ย 
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
jaxconf
ย 
HTML5 Refresher
HTML5 Refresher
Ivano Malavolta
ย 
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Codemotion
ย 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen
ย 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
ย 
Writing & Using Web Services
Writing & Using Web Services
Rajarshi Guha
ย 
Server side
Server side
philipsinter
ย 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra
ย 
Web services - A Practical Approach
Web services - A Practical Approach
Madhaiyan Muthu
ย 
Service Oriented Integration With ServiceMix
Service Oriented Integration With ServiceMix
Bruce Snyder
ย 
Web-Socket
Web-Socket
Pankaj Kumar Sharma
ย 
Web development with ASP.NET Web API
Web development with ASP.NET Web API
Damir Dobric
ย 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
ย 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
Eyal Vardi
ย 
SOAP-based Web Services
SOAP-based Web Services
Katrien Verbert
ย 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
ย 
Java servlets and CGI
Java servlets and CGI
lavanya marichamy
ย 
Excellent rest using asp.net web api
Excellent rest using asp.net web api
Maurice De Beijer [MVP]
ย 
Servlets
Servlets
ZainabNoorGul
ย 
Interoperable Web Services with JAX-WS
Interoperable Web Services with JAX-WS
Carol McDonald
ย 
An Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
ย 
Web Tech Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
ย 
Servlets
Servlets
Sasidhar Kothuru
ย 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
Arun Gupta
ย 
Databases and agile development - Dwight Merriman (MongoDB)
Databases and agile development - Dwight Merriman (MongoDB)
jaxLondonConference
ย 
What makes Groovy Groovy - Guillaume Laforge (Pivotal)
What makes Groovy Groovy - Guillaume Laforge (Pivotal)
jaxLondonConference
ย 

More Related Content

What's hot (19)

Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
ย 
Writing & Using Web Services
Writing & Using Web Services
Rajarshi Guha
ย 
Server side
Server side
philipsinter
ย 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra
ย 
Web services - A Practical Approach
Web services - A Practical Approach
Madhaiyan Muthu
ย 
Service Oriented Integration With ServiceMix
Service Oriented Integration With ServiceMix
Bruce Snyder
ย 
Web-Socket
Web-Socket
Pankaj Kumar Sharma
ย 
Web development with ASP.NET Web API
Web development with ASP.NET Web API
Damir Dobric
ย 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
ย 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
Eyal Vardi
ย 
SOAP-based Web Services
SOAP-based Web Services
Katrien Verbert
ย 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
ย 
Java servlets and CGI
Java servlets and CGI
lavanya marichamy
ย 
Excellent rest using asp.net web api
Excellent rest using asp.net web api
Maurice De Beijer [MVP]
ย 
Servlets
Servlets
ZainabNoorGul
ย 
Interoperable Web Services with JAX-WS
Interoperable Web Services with JAX-WS
Carol McDonald
ย 
An Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
ย 
Web Tech Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
ย 
Servlets
Servlets
Sasidhar Kothuru
ย 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
ย 
Writing & Using Web Services
Writing & Using Web Services
Rajarshi Guha
ย 
Server side
Server side
philipsinter
ย 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra
ย 
Web services - A Practical Approach
Web services - A Practical Approach
Madhaiyan Muthu
ย 
Service Oriented Integration With ServiceMix
Service Oriented Integration With ServiceMix
Bruce Snyder
ย 
Web development with ASP.NET Web API
Web development with ASP.NET Web API
Damir Dobric
ย 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
ย 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
Eyal Vardi
ย 
SOAP-based Web Services
SOAP-based Web Services
Katrien Verbert
ย 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
ย 
Java servlets and CGI
Java servlets and CGI
lavanya marichamy
ย 
Excellent rest using asp.net web api
Excellent rest using asp.net web api
Maurice De Beijer [MVP]
ย 
Interoperable Web Services with JAX-WS
Interoperable Web Services with JAX-WS
Carol McDonald
ย 
An Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
ย 
Web Tech Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
ย 

Viewers also liked (20)

Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
Arun Gupta
ย 
Databases and agile development - Dwight Merriman (MongoDB)
Databases and agile development - Dwight Merriman (MongoDB)
jaxLondonConference
ย 
What makes Groovy Groovy - Guillaume Laforge (Pivotal)
What makes Groovy Groovy - Guillaume Laforge (Pivotal)
jaxLondonConference
ย 
Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)
Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)
jaxLondonConference
ย 
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
jaxLondonConference
ย 
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
jaxLondonConference
ย 
Little words of wisdom for the developer - Guillaume Laforge (Pivotal)
Little words of wisdom for the developer - Guillaume Laforge (Pivotal)
jaxLondonConference
ย 
Big data from the LHC commissioning: practical lessons from big science - Sim...
Big data from the LHC commissioning: practical lessons from big science - Sim...
jaxLondonConference
ย 
Big Events, Mob Scale - Darach Ennis (Push Technology)
Big Events, Mob Scale - Darach Ennis (Push Technology)
jaxLondonConference
ย 
Are Hypermedia APIs Just Hype? - Aaron Phethean (Temenos) & Daniel Feist (Mul...
Are Hypermedia APIs Just Hype? - Aaron Phethean (Temenos) & Daniel Feist (Mul...
jaxLondonConference
ย 
Bringing your app to the web with Dart - Chris Buckett (Entity Group)
Bringing your app to the web with Dart - Chris Buckett (Entity Group)
jaxLondonConference
ย 
Practical Performance: Understand the Performance of Your Application - Chris...
Practical Performance: Understand the Performance of Your Application - Chris...
jaxLondonConference
ย 
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
jaxLondonConference
ย 
Legal and ethical considerations redone
Legal and ethical considerations redone
Nicole174
ย 
How Windows 10 will change the way we use devices
How Windows 10 will change the way we use devices
Commelius Solutions
ย 
A real-time architecture using Hadoop & Storm - Nathan Bijnens & Geert Van La...
A real-time architecture using Hadoop & Storm - Nathan Bijnens & Geert Van La...
jaxLondonConference
ย 
45 second video proposal
45 second video proposal
Nicole174
ย 
Garbage Collection: the Useful Parts - Martijn Verburg & Dr John Oliver (jCla...
Garbage Collection: the Useful Parts - Martijn Verburg & Dr John Oliver (jCla...
jaxLondonConference
ย 
How Hailo fuels its growth using NoSQL storage and analytics - Dave Gardner (...
How Hailo fuels its growth using NoSQL storage and analytics - Dave Gardner (...
jaxLondonConference
ย 
Scaling Scala to the database - Stefan Zeiger (Typesafe)
Scaling Scala to the database - Stefan Zeiger (Typesafe)
jaxLondonConference
ย 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
Arun Gupta
ย 
Databases and agile development - Dwight Merriman (MongoDB)
Databases and agile development - Dwight Merriman (MongoDB)
jaxLondonConference
ย 
What makes Groovy Groovy - Guillaume Laforge (Pivotal)
What makes Groovy Groovy - Guillaume Laforge (Pivotal)
jaxLondonConference
ย 
Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)
Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)
jaxLondonConference
ย 
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
Designing and Building a Graph Database Application - Ian Robinson (Neo Techn...
jaxLondonConference
ย 
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
jaxLondonConference
ย 
Little words of wisdom for the developer - Guillaume Laforge (Pivotal)
Little words of wisdom for the developer - Guillaume Laforge (Pivotal)
jaxLondonConference
ย 
Big data from the LHC commissioning: practical lessons from big science - Sim...
Big data from the LHC commissioning: practical lessons from big science - Sim...
jaxLondonConference
ย 
Big Events, Mob Scale - Darach Ennis (Push Technology)
Big Events, Mob Scale - Darach Ennis (Push Technology)
jaxLondonConference
ย 
Are Hypermedia APIs Just Hype? - Aaron Phethean (Temenos) & Daniel Feist (Mul...
Are Hypermedia APIs Just Hype? - Aaron Phethean (Temenos) & Daniel Feist (Mul...
jaxLondonConference
ย 
Bringing your app to the web with Dart - Chris Buckett (Entity Group)
Bringing your app to the web with Dart - Chris Buckett (Entity Group)
jaxLondonConference
ย 
Practical Performance: Understand the Performance of Your Application - Chris...
Practical Performance: Understand the Performance of Your Application - Chris...
jaxLondonConference
ย 
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
jaxLondonConference
ย 
Legal and ethical considerations redone
Legal and ethical considerations redone
Nicole174
ย 
How Windows 10 will change the way we use devices
How Windows 10 will change the way we use devices
Commelius Solutions
ย 
A real-time architecture using Hadoop & Storm - Nathan Bijnens & Geert Van La...
A real-time architecture using Hadoop & Storm - Nathan Bijnens & Geert Van La...
jaxLondonConference
ย 
45 second video proposal
45 second video proposal
Nicole174
ย 
Garbage Collection: the Useful Parts - Martijn Verburg & Dr John Oliver (jCla...
Garbage Collection: the Useful Parts - Martijn Verburg & Dr John Oliver (jCla...
jaxLondonConference
ย 
How Hailo fuels its growth using NoSQL storage and analytics - Dave Gardner (...
How Hailo fuels its growth using NoSQL storage and analytics - Dave Gardner (...
jaxLondonConference
ย 
Scaling Scala to the database - Stefan Zeiger (Typesafe)
Scaling Scala to the database - Stefan Zeiger (Typesafe)
jaxLondonConference
ย 
Ad

Similar to Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta (Red Hat) (20)

WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
Bruno Borges
ย 
T2
T2
Mo Ch
ย 
JAX RS 2.0 - OTN Bangalore 2013
JAX RS 2.0 - OTN Bangalore 2013
Jagadish Prasath
ย 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Arun Gupta
ย 
112815 java ee8_davidd
112815 java ee8_davidd
Takashi Ito
ย 
H2O 3 REST API Overview
H2O 3 REST API Overview
Sri Ambati
ย 
H2O 3 REST API Overview
H2O 3 REST API Overview
Raymond Peck
ย 
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 Services
Arun Gupta
ย 
JAX-RS.next
JAX-RS.next
Michal Gajdos
ย 
Web Applications Development
Web Applications Development
riround
ย 
Fight empire-html5
Fight empire-html5
Bhakti Mehta
ย 
Socket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
ย 
Sockets
Sockets
sivindia
ย 
Get Hip with JHipster - GIDS 2019
Get Hip with JHipster - GIDS 2019
Matt Raible
ย 
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 devices
ciklum_ods
ย 
Servlet
Servlet
Rajesh Roky
ย 
REST made simple with Java
REST made simple with Java
Niklas Gustavsson
ย 
Think async
Think async
Bhakti Mehta
ย 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
Bruno Borges
ย 
T2
T2
Mo Ch
ย 
JAX RS 2.0 - OTN Bangalore 2013
JAX RS 2.0 - OTN Bangalore 2013
Jagadish Prasath
ย 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Arun Gupta
ย 
112815 java ee8_davidd
112815 java ee8_davidd
Takashi Ito
ย 
H2O 3 REST API Overview
H2O 3 REST API Overview
Sri Ambati
ย 
H2O 3 REST API Overview
H2O 3 REST API Overview
Raymond Peck
ย 
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 Services
Arun Gupta
ย 
JAX-RS.next
JAX-RS.next
Michal Gajdos
ย 
Web Applications Development
Web Applications Development
riround
ย 
Fight empire-html5
Fight empire-html5
Bhakti Mehta
ย 
Socket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
ย 
Sockets
Sockets
sivindia
ย 
Get Hip with JHipster - GIDS 2019
Get Hip with JHipster - GIDS 2019
Matt Raible
ย 
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 devices
ciklum_ods
ย 
Servlet
Servlet
Rajesh Roky
ย 
REST made simple with Java
REST made simple with Java
Niklas Gustavsson
ย 
Think async
Think async
Bhakti Mehta
ย 
Ad

More from jaxLondonConference (19)

Conflict Free Replicated Data-types in Eventually Consistent Systems - Joel J...
Conflict Free Replicated Data-types in Eventually Consistent Systems - Joel J...
jaxLondonConference
ย 
JVM Support for Multitenant Applications - Steve Poole (IBM)
JVM Support for Multitenant Applications - Steve Poole (IBM)
jaxLondonConference
ย 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
jaxLondonConference
ย 
Why other ppl_dont_get_it
Why other ppl_dont_get_it
jaxLondonConference
ย 
Introducing Vert.x 2.0 - Taking polyglot application development to the next ...
Introducing Vert.x 2.0 - Taking polyglot application development to the next ...
jaxLondonConference
ย 
How Java got its Mojo Back - James Governor (Redmonk)
How Java got its Mojo Back - James Governor (Redmonk)
jaxLondonConference
ย 
Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)
jaxLondonConference
ย 
Streams and Things - Darach Ennis (Ubiquiti Networks)
Streams and Things - Darach Ennis (Ubiquiti Networks)
jaxLondonConference
ย 
The Java Virtual Machine is Over - The Polyglot VM is here - Marcus Lagergren...
The Java Virtual Machine is Over - The Polyglot VM is here - Marcus Lagergren...
jaxLondonConference
ย 
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
ย 
Exploring the Talend unified Big Data toolset for sentiment analysis - Ben Br...
Exploring the Talend unified Big Data toolset for sentiment analysis - Ben Br...
jaxLondonConference
ย 
The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)
jaxLondonConference
ย 
TDD at scale - Mash Badar (UBS)
TDD at scale - Mash Badar (UBS)
jaxLondonConference
ย 
Run Your Java Code on Cloud Foundry - Andy Piper (Pivotal)
Run Your Java Code on Cloud Foundry - Andy Piper (Pivotal)
jaxLondonConference
ย 
Put your Java apps to sleep? Find out how - John Matthew Holt (Waratek)
Put your Java apps to sleep? Find out how - John Matthew Holt (Waratek)
jaxLondonConference
ย 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
jaxLondonConference
ย 
Do You Like Coffee with Your dessert? Java and the Raspberry Pi - Simon Ritte...
Do You Like Coffee with Your dessert? Java and the Raspberry Pi - Simon Ritte...
jaxLondonConference
ย 
Large scale, interactive ad-hoc queries over different datastores with Apache...
Large scale, interactive ad-hoc queries over different datastores with Apache...
jaxLondonConference
ย 
Designing Resilient Application Platforms with Apache Cassandra - Hayato Shim...
Designing Resilient Application Platforms with Apache Cassandra - Hayato Shim...
jaxLondonConference
ย 
Conflict Free Replicated Data-types in Eventually Consistent Systems - Joel J...
Conflict Free Replicated Data-types in Eventually Consistent Systems - Joel J...
jaxLondonConference
ย 
JVM Support for Multitenant Applications - Steve Poole (IBM)
JVM Support for Multitenant Applications - Steve Poole (IBM)
jaxLondonConference
ย 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
jaxLondonConference
ย 
Why other ppl_dont_get_it
Why other ppl_dont_get_it
jaxLondonConference
ย 
Introducing Vert.x 2.0 - Taking polyglot application development to the next ...
Introducing Vert.x 2.0 - Taking polyglot application development to the next ...
jaxLondonConference
ย 
How Java got its Mojo Back - James Governor (Redmonk)
How Java got its Mojo Back - James Governor (Redmonk)
jaxLondonConference
ย 
Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)
jaxLondonConference
ย 
Streams and Things - Darach Ennis (Ubiquiti Networks)
Streams and Things - Darach Ennis (Ubiquiti Networks)
jaxLondonConference
ย 
The Java Virtual Machine is Over - The Polyglot VM is here - Marcus Lagergren...
The Java Virtual Machine is Over - The Polyglot VM is here - Marcus Lagergren...
jaxLondonConference
ย 
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
ย 
Exploring the Talend unified Big Data toolset for sentiment analysis - Ben Br...
Exploring the Talend unified Big Data toolset for sentiment analysis - Ben Br...
jaxLondonConference
ย 
The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)
jaxLondonConference
ย 
TDD at scale - Mash Badar (UBS)
TDD at scale - Mash Badar (UBS)
jaxLondonConference
ย 
Run Your Java Code on Cloud Foundry - Andy Piper (Pivotal)
Run Your Java Code on Cloud Foundry - Andy Piper (Pivotal)
jaxLondonConference
ย 
Put your Java apps to sleep? Find out how - John Matthew Holt (Waratek)
Put your Java apps to sleep? Find out how - John Matthew Holt (Waratek)
jaxLondonConference
ย 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
jaxLondonConference
ย 
Do You Like Coffee with Your dessert? Java and the Raspberry Pi - Simon Ritte...
Do You Like Coffee with Your dessert? Java and the Raspberry Pi - Simon Ritte...
jaxLondonConference
ย 
Large scale, interactive ad-hoc queries over different datastores with Apache...
Large scale, interactive ad-hoc queries over different datastores with Apache...
jaxLondonConference
ย 
Designing Resilient Application Platforms with Apache Cassandra - Hayato Shim...
Designing Resilient Application Platforms with Apache Cassandra - Hayato Shim...
jaxLondonConference
ย 

Recently uploaded (20)

Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
ย 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
ย 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
ย 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
ย 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
ย 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
ย 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
ย 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
ย 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
ย 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
ย 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
ย 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
ย 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
ย 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
ย 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
ย 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
ย 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
ย 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
ย 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
ย 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
ย 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
ย 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
ย 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
ย 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
ย 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
ย 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
ย 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
ย 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
ย 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
ย 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
ย 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
ย 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
ย 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
ย 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
ย 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
ย 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
ย 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
ย 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
ย 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
ย 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
ย 

Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta (Red Hat)

  • 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.