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

Host: server.example.com

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==

Origin: http://example.com

Sec-WebSocket-Protocol: chat, superchat

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

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

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



@ServerEndpoint("/hello")

public class HelloBean {



@OnMessage

public String sayHello(String name) {

return “Hello “ + name;

}

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

value="/hello",

encoders={MyMessage.class},

decoders={MyMessage.class}

)

public class MyEndpoint {

. . .

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

private JsonObject jsonObject;



public MyMessage decode(String s) {

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

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

return true; // Only if can process the payload

}"
"
public String encode(MyMessage myMessage) {

return myMessage.jsonObject.toString();

}

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



public MyMessage decode(byte[] bytes) {

. . .

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

. . .

return true; // Only if can process the payload

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

. . .

}

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



@OnOpen

public void onOpen(Session peer) {

peers.add(peer);

}



@OnClose

public void onClose(Session peer) {

peers.remove(peer);

}



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



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

peer.getBasicRemote().sendObject(message);

}

}

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

public class HelloClient {

@OnMessage

public void message(String message, Session session) {

// process message from server

}

}

"
WebSocketContainer c = ContainerProvider.getWebSocketContainer();

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



@Override

public void onOpen(Session session) {

session.addMessageHandler(new MessageHandler.Text() {

public void onMessage(String name) {

try {

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

} catch (IOException ex) {

}

} 

});

}

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

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

console.log(event.data);

}

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

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



@GET

@Path("events”)

@Produces(SseFeature.SERVER_SENT_EVENTS)

public EventOutput fruitEvents() {

final EventOutput eventOutput = new EventOutput();

BROADCASTER.add(eventOutput);

return eventOutput;

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

@Consumes(MediaType.APPLICATION_FORM_URLENCODED)

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

FRUITS.add(fruit);



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

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



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

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

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

Recommended

Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
Arun Gupta
 
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
 
Server-Side Programming Primer
Server-Side Programming Primer
Ivano Malavolta
 
WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0
Jeffrey West
 
Java Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application Security
IMC Institute
 
What's new in DWR version 3
What's new in DWR version 3
Joe Walker
 
JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web Services
Arun Gupta
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
Carol McDonald
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
Neil Ghosh
 
RESTEasy
RESTEasy
Massimiliano Dessì
 
Java EE and Spring Side-by-Side
Java EE and Spring Side-by-Side
Reza Rahman
 
Think async
Think async
Bhakti Mehta
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2
Geoffrey Fox
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
reneechemel
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
Bhakti Mehta
 
Rest Security with JAX-RS
Rest Security with JAX-RS
Frank Kim
 
Writing & Using Web Services
Writing & Using Web Services
Rajarshi Guha
 
OAuth: Trust Issues
OAuth: Trust Issues
Lorna Mitchell
 
RESTful Web Services with Spring MVC
RESTful Web Services with Spring MVC
digitalsonic
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RS
Arun Gupta
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
Ulf Wendel
 
Introduction to Ajax programming
Introduction to Ajax programming
Fulvio Corno
 
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
jaxLondonConference
 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Arun Gupta
 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
Bruno Borges
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
David Delabassee
 
WebSockets in JEE 7
WebSockets in JEE 7
Shahzad Badar
 

More Related Content

What's hot (17)

RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
Carol McDonald
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
Neil Ghosh
 
RESTEasy
RESTEasy
Massimiliano Dessì
 
Java EE and Spring Side-by-Side
Java EE and Spring Side-by-Side
Reza Rahman
 
Think async
Think async
Bhakti Mehta
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2
Geoffrey Fox
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
reneechemel
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
Bhakti Mehta
 
Rest Security with JAX-RS
Rest Security with JAX-RS
Frank Kim
 
Writing & Using Web Services
Writing & Using Web Services
Rajarshi Guha
 
OAuth: Trust Issues
OAuth: Trust Issues
Lorna Mitchell
 
RESTful Web Services with Spring MVC
RESTful Web Services with Spring MVC
digitalsonic
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RS
Arun Gupta
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
Ulf Wendel
 
Introduction to Ajax programming
Introduction to Ajax programming
Fulvio Corno
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
Carol McDonald
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
Neil Ghosh
 
Java EE and Spring Side-by-Side
Java EE and Spring Side-by-Side
Reza Rahman
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2
Geoffrey Fox
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
reneechemel
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
Bhakti Mehta
 
Rest Security with JAX-RS
Rest Security with JAX-RS
Frank Kim
 
Writing & Using Web Services
Writing & Using Web Services
Rajarshi Guha
 
RESTful Web Services with Spring MVC
RESTful Web Services with Spring MVC
digitalsonic
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RS
Arun Gupta
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
Ulf Wendel
 
Introduction to Ajax programming
Introduction to Ajax programming
Fulvio Corno
 

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

Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
jaxLondonConference
 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Arun Gupta
 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
Bruno Borges
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
David Delabassee
 
WebSockets in JEE 7
WebSockets in JEE 7
Shahzad Badar
 
WebSocket in Enterprise Applications 2015
WebSocket in Enterprise Applications 2015
Pavel Bucek
 
Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocket
Mauricio "Maltron" Leal
 
Web sockets in java EE 7 - JavaOne 2013
Web sockets in java EE 7 - JavaOne 2013
Siva Arunachalam
 
Web-Socket
Web-Socket
Pankaj Kumar Sharma
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
James Falkner
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)
Pavel Bucek
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
Viktor Gamov
 
Fight empire-html5
Fight empire-html5
Bhakti Mehta
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentation
Volodymyr Lavrynovych
 
JUG louvain websockets
JUG louvain websockets
Marc Tritschler
 
Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
WebSockets in Enterprise Applications
WebSockets in Enterprise Applications
Pavel Bucek
 
Client server chat application
Client server chat application
Samsil Arefin
 
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Arun Gupta
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
Naresh Chintalcheru
 
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
jaxLondonConference
 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Arun Gupta
 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
Bruno Borges
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
David Delabassee
 
WebSocket in Enterprise Applications 2015
WebSocket in Enterprise Applications 2015
Pavel Bucek
 
Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocket
Mauricio "Maltron" Leal
 
Web sockets in java EE 7 - JavaOne 2013
Web sockets in java EE 7 - JavaOne 2013
Siva Arunachalam
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
James Falkner
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)
Pavel Bucek
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
Viktor Gamov
 
Fight empire-html5
Fight empire-html5
Bhakti Mehta
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentation
Volodymyr Lavrynovych
 
Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
WebSockets in Enterprise Applications
WebSockets in Enterprise Applications
Pavel Bucek
 
Client server chat application
Client server chat application
Samsil Arefin
 
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Arun Gupta
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
Naresh Chintalcheru
 
Ad

More from Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
Codemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
Codemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
Codemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Codemotion
 
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
Codemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
Codemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
Codemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Codemotion
 
Ad

Recently uploaded (20)

Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 

Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta

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