• Save
Getting Started with WebSocket and Server-Sent Events in Java
Upcoming SlideShare
Loading in...5
×
 

Getting Started with WebSocket and Server-Sent Events in Java

on

  • 3,346 views

Getting Started with WebSocket and Server-Sent Events in Java

Getting Started with WebSocket and Server-Sent Events in Java

Statistics

Views

Total Views
3,346
Views on SlideShare
3,192
Embed Views
154

Actions

Likes
14
Downloads
0
Comments
0

9 Embeds 154

https://twitter.com 76
http://confluence.austin.polycom.com 45
http://glassfish.collected.info 23
http://localhost 4
http://www.feedspot.com 2
http://feeds.feedburner.com 1
http://webcache.googleusercontent.com 1
http://hero-worshiper6.zulti.com 1
http://confluence.polycom.com 1
More...

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Getting Started with WebSocket and Server-Sent Events in Java Getting Started with WebSocket and Server-Sent Events in Java Presentation Transcript

  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.1
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.2Getting Started withWebSocket and Server-SentEvent in JavaArun Guptablogs.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 16ProgramAgenda§  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.4Interactive 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.5WebSocket 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.6Establish a connectionClientHandshake RequestHandshake ResponseServer
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.7Handshake RequestGET /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.8Handshake ResponseHTTP/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.9ServerClientHandshake RequestHandshake ResponseConnected !Establishing a Connection
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.10Peer(server)Peer(client)Connected !open openclosemessageerrormessagemessagemessagemessageDisconnectedWebSocket Lifecycle
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.11WebSocket APIwww.w3.org/TR/websockets/
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.12 http://caniuse.com/websocketsBrowser Support
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.13
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.14Java API for WebSocket Features§  API for WebSocket Server/Client Endpoints–  Annotated (@ServerEndpoint, @ClientEndpoint)–  Programmatic (Endpoint)§  WebSocket opening handshake negotiation§  Lifecycle callback handlers§  Packaging with Java EE applications
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.15Annotated Endpointimport 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.16AnnotationsAnnotation 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"methodparameterFlags 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 Attributesvalue"Relative URI or URI templatee.g. /hello or /chat/{subscriber-level}decoders" list of message decoder classnamesencoders" list of message encoder classnamessubprotocols" list of the names of the supported subprotocols
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.18Custom Payloads@ServerEndpoint(
value="/hello",
encoders={MyMessage.class},
decoders={MyMessage.class}
)
public class MyEndpoint {
. . .
}"""
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.19Custom Payloads – Textpublic 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.20Custom Payloads – Binarypublic 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.21Which 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 andboolean, 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 classequivalent or any type for which there is a encoder
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.22Sample 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”)Stringisbn, @PathParam(“store”)String store);"
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.23Chat 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.24Chat 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.25https://blogs.oracle.com/arungupta/entry/collaborative_whiteboard_using_websocket_in
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.26WebSocket 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.27Programmatic Endpointpublic 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.28How to view WebSocket messages ?Capture traffic on loopback
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.29How to view WebSocket messages ?chrome://net-internals -> Sockets -> View live sockets
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.30Server-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.31EventSource APIdev.w3.org/html5/eventsource/
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.32Server-Sent Events Examplevar 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.33Server-Sent Events Exampleprivate 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.34Server-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 indata
BROADCASTER.broadcast(new OutboundEvent.Builder().name("size").data(Integer.class,FRUITS.size()).build());
}
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.35WebSocket and Server-Sent EventCompeting technologies ?WebSocket Server-Sent EventOver a custom protocol Over simple HTTPFull Duplex, Bi-directional Server-Push Only, Client->Serveris out-of-band (higher latency)Native support in most browsers Can be poly-filled to backportNot straight forward protocol Simpler protocol
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.36WebSocket and Server-Sent EventCompeting technologies ?WebSocket Server-Sent EventPre-defined message handlers Arbitrary eventsApplication-specific Built-in support for re-connectionand event idRequire server and/or proxyconfigurationsNo server or proxy changesrequiredArrayBuffer and Blob No support for binary types
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.37Resources§  Java API for WebSocket–  Specification: jcp.org/en/jsr/detail?id=356–  Reference Implementation: java.net/projects/tyrus–  Integrated in GlassFish Server 4.0–  Part of Java EE 7§  Server-Sent Event–  Integrated in Jersey and GlassFish Server 4.0–  Not part of Java EE 7
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.38The preceding material is intended to outline our general productdirection. It is intended for information purposes only, and may not beincorporated into any contract. It is not a commitment to deliver anymaterial, code, or functionality, and should not be relied upon in makingpurchasing decisions. The development, release, and timing of anyfeatures or functionality described for Oracle’s products remains at thesole discretion of Oracle.
  • Copyright © 2013, Oracle and/or its affiliates. All rights reserved.39