Getting started with Websocket and Server-sent Events using Java - Arun Gupta

492 views

Published on

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. Together, they bring new opportunities for efficient server-push and peer-to-peer communication, providing the basis for a new generation of interactive and “live” Web applications. This session provides a primer on WebSocket and Server-Sent Events and their supported use cases.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
492
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Getting started with Websocket and Server-sent Events using Java - Arun Gupta

  1. 1. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.1
  2. 2. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.2Getting Started withWebSocket and Server-SentEvent in JavaArun Guptablogs.oracle.com/arungupta, @arungupta
  3. 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 16ProgramAgenda§  WebSocket Primer§  Getting Started with WebSocket§  Server-Sent Event Primer§  Getting Started with Server-Sent Event§  Resources
  4. 4. 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
  5. 5. 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
  6. 6. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.6Establish a connectionClientHandshake RequestHandshake ResponseServer
  7. 7. 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 "
  8. 8. 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 "
  9. 9. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.9ServerClientHandshake RequestHandshake ResponseConnected !Establishing a Connection
  10. 10. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.10Peer(server)Peer(client)Connected !open openclosemessageerrormessagemessagemessagemessageDisconnectedWebSocket Lifecycle
  11. 11. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.11WebSocket APIwww.w3.org/TR/websockets/
  12. 12. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.12 http://caniuse.com/websocketsBrowser Support
  13. 13. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.13
  14. 14. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.14Java 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. 15. 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;
}
}"
  16. 16. 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
  17. 17. 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
  18. 18. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.18Custom Payloads@ServerEndpoint(
value="/hello",
encoders={MyMessage.class},
decoders={MyMessage.class}
)
public class MyEndpoint {
. . .
}"""
  19. 19. 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();
}
}"
  20. 20. 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) {
. . .
}
}"
  21. 21. 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
  22. 22. 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);"
  23. 23. 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);
}

. . ."
  24. 24. 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);
}
}
}"
  25. 25. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.25WebSocket 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. 26. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.26Programmatic 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) {
}
} 
});
}
}"
  27. 27. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.27How to view WebSocket messages ?Capture traffic on loopback
  28. 28. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.28How to view WebSocket messages ?chrome://net-internals -> Sockets -> View live sockets
  29. 29. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.29Server-Sent Events§  Part of HTML5 Specification§  Server-push notifications§  Cross-browser JavaScript API: EventSource"§  Message callbacks§  MIME type: text/eventstream"
  30. 30. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.30EventSource APIdev.w3.org/html5/eventsource/
  31. 31. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.31Server-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
  32. 32. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.32Server-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;
}
  33. 33. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.33Server-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());
}
  34. 34. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.34WebSocket 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
  35. 35. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.35WebSocket 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
  36. 36. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.36Resources§  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. 37. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.37

×