Server-Sent Events defines a standard technology for server-push notifications. WebSocket attempts to solve the issues and limitations of HTTP for real-time communication by providing a full-duplex communication over a single TCP channel. This session provides a primer on WebSocket and Server-Sent Events. It examines the efforts under way to support WebSocket in the Java programming model, from a simple annotation-driven programming model and integration in the Java EE containers using JSR 356. The session also explains how Server-Sent Events can be easily written using Jersey, the Reference Implementation for JAX-RS 2. The attendees will learn how to leverage WebSocket and Server-Sent Events in their web applications using several code samples though out the talk. Simple “Hello World” to more elaborate Collaborative Whiteboard applications will show different features of both the technologies. A complete development using NetBeans, deployment on GlassFish, and debugging using Chrome will be shown
"> Server-Sent Events defines a standard technology for server-push notifications. WebSocket attempts to solve the issues and limitations of HTTP for real-time communication by providing a full-duplex communication over a single TCP channel. This session provides a primer on WebSocket and Server-Sent Events. It examines the efforts under way to support WebSocket in the Java programming model, from a simple annotation-driven programming model and integration in the Java EE containers using JSR 356. The session also explains how Server-Sent Events can be easily written using Jersey, the Reference Implementation for JAX-RS 2. The attendees will learn how to leverage WebSocket and Server-Sent Events in their web applications using several code samples though out the talk. Simple “Hello World” to more elaborate Collaborative Whiteboard applications will show different features of both the technologies. A complete development using NetBeans, deployment on GlassFish, and debugging using Chrome will be shown
" /> Server-Sent Events defines a standard technology for server-push notifications. WebSocket attempts to solve the issues and limitations of HTTP for real-time communication by providing a full-duplex communication over a single TCP channel. This session provides a primer on WebSocket and Server-Sent Events. It examines the efforts under way to support WebSocket in the Java programming model, from a simple annotation-driven programming model and integration in the Java EE containers using JSR 356. The session also explains how Server-Sent Events can be easily written using Jersey, the Reference Implementation for JAX-RS 2. The attendees will learn how to leverage WebSocket and Server-Sent Events in their web applications using several code samples though out the talk. Simple “Hello World” to more elaborate Collaborative Whiteboard applications will show different features of both the technologies. A complete development using NetBeans, deployment on GlassFish, and debugging using Chrome will be shown
">

Presentation Getting Started with WebSocket and SSE

Server-Sent Events defines a standard technology for server-push notifications. WebSocket attempts to solve the issues and limitations of HTTP for real-time communication by providing a full-duplex communication over a single TCP channel. This session provides a primer on WebSocket and Server-Sent Events. It examines the efforts under way to support WebSocket in the Java programming model, from a simple annotation-driven programming model and integration in the Java EE containers using JSR 356. The session also explains how Server-Sent Events can be easily written using Jersey, the Reference Implementation for JAX-RS 2. The attendees will learn how to leverage WebSocket and Server-Sent Events in their web applications using several code samples though out the talk. Simple “Hello World” to more elaborate Collaborative Whiteboard applications will show different features of both the technologies. A complete development using NetBeans, deployment on GlassFish, and debugging using Chrome will be shown

Speakers


PDF: slides.pdf

Slides

Getting Started with

Getting Started with WebSocket and Server-Sent Event in Java Arun Gupta blogs.oracle.com/arungupta, @arungupta 2 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Program

Program Agenda §  WebSocket Primer §  Getting Started with WebSocket §  Server-Sent Event Primer §  Getting Started with Server-Sent Event §  Resources 3 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. 2012, Insert Information Protection Policy Classification from Slide 16

Interactive Web Sites

Interactive Web Sites §  HTTP is half-duplex §  HTTP is verbose §  Hacks for Server Push –  Polling –  Long Polling –  Comet/Ajax §  Complex, Inefficient, Wasteful 4 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

WebSocket to the Rescue

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

Establish a connection

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

Handshake Request

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

Handshake Response

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

Establishing a Connection

Establishing a Connection Handshake Request Client Server Handshake Response Connected ! 9 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

WebSocket Lifecycle

WebSocket Lifecycle Connected ! open Peer (client) open message message message message error message close Disconnected 10 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Peer (server)

WebSocket API

WebSocket API www.w3.org/TR/websockets/ 11 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Browser Support

Browser Support 12 Copyright © 2013, Oracle and/or its affiliates. All rights reserved. http://caniuse.com/websockets

13

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

Java API for WebSocket Features

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

Hello World

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

Annotations

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" 16 method method Intercepts errors during a conversation Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

@ServerEndpoint Attributes

@ServerEndpoint Attributes value" decoders" list of message decoder classnames encoders" list of message encoder classnames subprotocols" 17 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

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

Custom Payloads – Text

Custom Payloads – Text public class MyMessage implements Decoder.Text, Encoder.Text {
 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();
 }
 }" 19 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.

Custom Payloads – Binary

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

WebSocket Client

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.

How to view WebSocket messages ?

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 ?

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

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

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

Server-Sent Events Example

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

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.

Server-Sent Events Example

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.

WebSocket and Server-Sent Event

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

WebSocket and Server-Sent Event

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

Resources

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

37

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