Introduction to the Java API for WebSocket (JSR 356)
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Introduction to the Java API for WebSocket (JSR 356)

on

  • 31,164 views

This session examines the efforts with JSR 356 to support WebSocket in the Java programming model, from its base-level integration in the Java Servlet and Java EE 7 containers to a new, easy-to-use ...

This session examines the efforts with JSR 356 to support WebSocket in the Java programming model, from its base-level integration in the Java Servlet and Java EE 7 containers to a new, easy-to-use API and tool set that is part of the standard enterprise Java platform.

The family of HTML5 technologies has pushed the pendulum away from thin client technologies and toward ever-more-capable Web clients running on today’s browsers. In particular, WebSocket brings new opportunities for efficient peer-to-peer communication, providing the basis for a new generation of interactive and “live” Web applications. JSR 356 brings these capabilities to server-side Java developers.

The session is a deep dive into JSR 356 including some demos.

Statistics

Views

Total Views
31,164
Views on SlideShare
19,876
Embed Views
11,288

Actions

Likes
13
Downloads
257
Comments
2

57 Embeds 11,288

https://blogs.oracle.com 6678
http://java.dzone.com 2703
http://ameblo.jp 899
http://orablogs-jp.blogspot.jp 266
http://cloud.feedly.com 180
http://glassfish.collected.info 96
http://s.ameblo.jp 70
http://feedspot.com 41
http://orga 37
http://www.feedspot.com 36
http://chemosurgical23.rssing.com 25
http://www.newsblur.com 22
http://feedly.com 22
http://blogs.oracle.com 17
http://plus.url.google.com 15
http://digg.com 13
http://newsblur.com 12
http://cuckoo9.okoza.com 12
http://blog.ameba.jp 12
https://twitter.com 11
http://prsync.com 10
http://webcache.googleusercontent.com 8
http://127.0.0.1 8
https://inoreader.com 8
http://reader.aol.com 7
http://orablogs-jp.blogspot.com 7
http://css.dzone.com 6
http://extradiocesan12.mlmlliao.com 5
http://xianguo.com 4
http://summary 4
http://www.feedly.com 4
http://feedreader.com 4
http://bloggers1033.rssing.com 4
https://trovepromo-tf.trove-stg.com 3
http://www.unitask.com 3
http://open.dapper.net 3
http://news.google.com 3
http://www-ig-opensocial.googleusercontent.com 3
http://translate.googleusercontent.com 2
https://www.inoreader.com 2
http://yoleoreader.com 2
https://feedly.com 2
http://feeds.iti.bz 2
http://de.flavors.me 2
http://www.dzone.com 2
http://flavors.me 2
http://rss.neurozone.fr 1
http://oracle.com 1
http://orablogs-jp.blogspot.com.au 1
http://www.tuicool.com 1
More...

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

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…
  • You'll have to wait until Tomcat catches up - I think there's some support in the latest version already, I haven't checked. You can use GlassFish or WildFly now.
    Are you sure you want to
    Your message goes here
    Processing…
  • How to use the example using a Tomcat server?
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • A logical websocket endpoint is represented in the Java WebSocket API as an instance of the Endpoint class. Developers may subclass the Endpoint class in order to intercept lifecycle events of the endpoint: those of a peer connecting, a peer disconnecting and an error being raised during the lifetime of the endpoint. <br /> The implementation must use at least one instance of the Endpoint class to represent the logical endpoint. Each instance of the Endpoint class may therefore handle connections to the endpoint from multiple peers. Some implementations may wish to use multiple instances of Endpoint to represent a logical endpoint, perhaps one instance per VM in a distributed server setting. <br /> The Java WebSocket API models the sequence of interactions between an endpoint and each of its peers using an instance of the Session class. The interactions between a peer and an endpoint begin with an open notification, followed by some number, possibly zero, of web socket messages between the endpoint and peer, followed by a close notification or error terminal to the connection. For each peer that is interacting with an endpoint, there is one Session instance that represents that interaction. The Session instance corresponding to the peer is passed to the Endpoint instance representing the endpoint at the key events in its lifecycle. <br />
  • The websocket protocol is a two-way protocol. Once established, the web socket protocol is symmetrical between the two parties in the conversation. The difference between a websocket ‘client’ and a websocket ‘server’ is only in the means by which the two parties are connected. In this specification, we will say that a websocket client is a websocket endpoint that initiates a connection to a peer. We will say that a websocket server is a websocket endpoint that is published an awaits connections from peers. In most deployments, a websocket client will connect to only one websocket server, and a websocket server will accept connections from several clients. <br />
  • The websocket protocol is a two-way protocol. Once established, the web socket protocol is symmetrical between the two parties in the conversation. The difference between a websocket ‘client’ and a websocket ‘server’ is only in the means by which the two parties are connected. In this specification, we will say that a websocket client is a websocket endpoint that initiates a connection to a peer. We will say that a websocket server is a websocket endpoint that is published an awaits connections from peers. In most deployments, a websocket client will connect to only one websocket server, and a websocket server will accept connections from several clients. <br />
  • The annotation defines that the decorated method be called whenever a new client has connected to this endpoint. The container notifies the method after the connection has been established [WSC-21]. The decorated method can only have optional Session parameter and zero to n String parameters annotated with a @WebSocketPathSegment annotation as parameters. If the Session parameter is present, the implementation must pass in the newly created Session corresponding to the new connection [WSC-22]. If the method throws an error, the implementation must pass this error to the onError method of the endpoint together with the session. <br /> The annotation defines that the decorated method be called whenever a new client is about to be disconnected from this endpoint. The container notifies the method before the connection is brought down [WSC-25]. The decorated method can only have optional Session parameter and zero to n String parameters annotated with a @WebSocketPathSegment annotation as parameters. If the Session parameter is present, the implementation must pass in the about-to-be ended Session corresponding to the connection [WSC-26]. If the method throws an error, the implementation must pass this error to the onError method of the endpoint together with the session. <br /> The annotation defines that the decorated method be called whenever an error is generated on any of the connections to this endpoint. The decorated method can only have optional Session parameter, mandatory Throwable parameter and zero to n String parameters annotated with a @WebSocketPathSegment annotation as parameters. If the Session parameter is present, the implementation must pass in the Session in which the error occurred to the connection [WSC-XX]. The container must pass the error as the Throwable parameter to this method. <br />
  • The encoders parameter contains a (possibly empty) list of Java classes that are to act as encoder components for this endpoint. These classes must implement some form of the Encoder interface, and have public no-arg constructors and be visible within the classpath of the application that this websocket endpoint is part of. The implementation must attempt to encode application objects of matching parametrized type as the encoder when they are attempted to be sent using the RemoteEndpoint API. <br /> The decoders parameter contains a (possibly empty) list of Java classes that are to act as decoder components for this endpoint. These classes must implement some form of the Decoder interface, and have public no-arg constructors and be visible within the classpath of the application that this websocket endpoint is part of. The implementation must attempt to decode web socket messages using the first appropriate decoder in the list and pass the message in decoded object form to the websocket endpoint [WSC-17]. The implementation uses the willDecode() method on the decoder to determine if the Decoder will match the incoming message. <br />
  • The method it decorates may have a number of forms <br /> - The first String parameter in its parameter list must be called by the container using the String form of the incoming message, if in text form [WSC-29]. <br /> - The first byte parameter in its parameter list must be called by the container using the byte array form of the incoming message, if in binary form [WSC-30]. <br /> If the parameter list contains a Session parameter, the implementation must use the Session object corresponding to the connection on which the message arrived [WSC-31]. <br /> - The method may have zero to n String parameters annotated with @WebSocketPathParameter. The method may or may not have a return type. If the method has a return type, the implementation must treat this return object as a web socket message to be immediately sent back to the sender of the incoming message [WSC-32]. It uses the usual mechanism of checking its supply of encoders in order to handle return types other than String or byte[]. <br />

Introduction to the Java API for WebSocket (JSR 356) Presentation Transcript

  • 1. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public1 Introduction to the Java API for WebSocket (JSR 356) Reza Rahman Java EE/GlassFish Evangelist Reza.Rahman@Oracle.com @reza_rahman
  • 2. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public2Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public Agenda  WebSocket 101  JSR 356: Java API for WebSocket  Demo
  • 3. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public3 WebSocket  HTTP/TCP based, bi-directional, full-duplex messaging  Originally proposed as part of HTML5  IETF-defined Protocol: RFC 6455  W3C defined JavaScript API
  • 4. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public4 Establish a connection Client Handshake Request Handshake Response Server
  • 5. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public5 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 © 2012, Oracle and/or its affiliates. All rights reserved. Public6 Handshake Response HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat
  • 7. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public7 Establishing a Connection ServerClient Handshake Request Handshake Response Connected !
  • 8. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public8 WebSocket Lifecycle ServerClient Connected ! open open close message message error message message Disconnected
  • 9. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public9 Browser Support
  • 10. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public10 Java API for WebSocket  Create WebSocket Endpoints – Interface-driven (Endpoint) – Annotation-driven (@ServerEndpoint)  Client and server APIs  Part of Java EE 7  SPI for extensions and data frames
  • 11. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public11 Basic API Tour
  • 12. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public12 Hello World Server public class HelloServer extends Endpoint { @Override public void onOpen(Session session, EndpointConfig configuration) { session.addMessageHandler( new MessageHandler.Whole<String>() { public void onMessage(String name) { try { session.getBasicRemote().sendText("Hello " + name); } catch (IOException ioe) { // Handle failure. } } }); } }
  • 13. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public13 Hello World Client public class HelloClient extends Endpoint { @Override public void onOpen(Session session, EndpointConfig configuration) { try { session.getBasicRemote().sendText("Hello you!"); } catch (IOException ioe) { ... } } }
  • 14. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public14 Client Server Configuration ServerContainer serverContainer = (ServerContainer) servletContext.getAttribute( "javax.websocket.server.ServerContainer"); ServerEndpointConfig serverConfiguration = ServerEndpointConfig.Builder.create( HelloServer.class, "/hello").build(); serverContainer.addEndpoint(serverConfiguration); ... URI clientURI = new URI("ws://myserver.com/websockets/hello"); WebSocketContainer container = ContainerProvider.getWebSocketContainer(); ClientEndpointConfig clientConfiguration = ClientEndpointConfig.Builder.create().build(); container.connectToServer(HelloClient.class, clientConfiguration, clientURI);
  • 15. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public15 Sending the Message Whole string * RemoteEndpoi nt.Basic sendText(String message) Binary data * RemoteEndpoi nt.Basic sendBinary(ByteBuffer message) String fragments RemoteEndpoi nt.Basic sendText(String part, boolean last) Binary data fragments RemoteEndpoi nt.Basic sendBinary(ByteBuffer part, boolean last) Blocking stream of text RemoteEndpoi nt.Basic Writer getSendWriter()) Blocking stream of binary data RemoteEndpoi nt.Basic OutputStream getSendStream() Custom object RemoteEndpoi nt.Basic sendObject(Object customObject) * Additional flavors: by completion, by future
  • 16. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public16 Receiving the Message Whole string MessageHandler .Whole<String> onMessage(String message) Binary data MessageHandler . Whole<ByteBuffer> onMessage(ByteBuffer message) String fragments MessageHandler .Partial<String> onMessage(String part, boolean last) Binary data fragments MessageHandler . Partial<ByteBuffe r> onMessage(ByteBuffer part, boolean last) Blocking stream of text MessageHandler .Whole<Reader> onMessage(Reader r) Blocking stream of binary data MessageHandler . Whole<InputSteam> onMessage(InputStream r) Custom object of type T MessageHandler .Whole<T> onMessage(T customObject)
  • 17. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public17 POJO + Annotations
  • 18. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public18 Hello World Annotations @ServerEndpoint("/hello") public class HelloBean { @OnMessage public String sayHello(String name) { return "Hello " + name; } }
  • 19. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public19 WebSocket Annotations Annotation Level Purpose @ServerEndpoint Class Turns a POJO into a WebSocket Server Endpoint @ClientEndpoint Class Turns a POJO into a WebSocket Client Endpoint @OnOpen Method Intercepts WebSocket Open events @OnClose Method Intercepts WebSocket Close events @OnMessage Method Intercepts WebSocket Message events @PathParam Method Parameter Flags a matched path segment of a URI- template @OnError Method Intercepts errors during a conversation
  • 20. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public20 @ServerEndpoint Attributes value Relative URI or URI template e.g. “/hello” or “/chat/{subscriber-level}” configurator Custom configuration decoders List of message decoder classnames encoders List of message encoder classnames subprotocols List of the names of the supported subprotocols
  • 21. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public21 Custom Payloads @ServerEndpoint( value="/hello", encoders={MyMessage.class}, decoders={MyMessage.class}) public class MyEndpoint { ... }
  • 22. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public22 Custom Payloads – Text public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> { private JsonObject jsonObject; public MyMessage decode(String s) { jsonObject = new 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(); } }
  • 23. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public23 Custom Payloads – Binary public class MyMessage implements Decoder.Binary<MyMessage>, Encoder.Binary<MyMessage> { ... public MyMessage decode(ByteBuffer bytes) { ... return this; } public boolean willDecode(ByteBuffer bytes) { ... return true; // Only if can process the payload } public ByteBuffer encode(MyMessage myMessage) { ... } }
  • 24. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public24 Chat Sample @Singleton @ServerEndpoint("/chat") public class ChatServer { private Set<Session> peers = new HashSet(); @OnOpen public void onOpen(Session peer) { peers.add(peer); } @OnClose public void onClose(Session peer) { peers.remove(peer); } ...
  • 25. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public25 Chat Sample (Continued) ... @OnMessage public void message(String message) { for (Session peer : peers) { peer.getBasicRemote().sendText(message); } } }
  • 26. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public26 URI Template Matching @ServerEndpoint("/orders/{order-id}") public class MyEndpoint { @OnMessage public void processOrder( @PathParam("order-id") String orderId) { ... } }
  • 27. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public27 @OnMessage Methods  A parameter type that can be decoded in incoming message – String, primitive, Reader, ByteBuffer, byte[], InputStream, or any type for which there is a decoder  An optional Session parameter  Boolean partial flag  0..n String parameters annotated with @PathParameter  A return type that can be encoded in outgoing message – String, primitive, Reader, ByteBuffer, byte[], InputStream, or any type for which there is an encoder
  • 28. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public28 Java WebSocket Demo https://github.com/m-reza-rahman/hello-websocket https://github.com/m-reza-rahman/whiteboard
  • 29. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public29 Try it Out! http://dlc.sun.com.edgesuite.net/glassfish/4.0.1/promoted/
  • 30. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public30 Java WebSocket Implementations Tomcat GlassFish TomEE
  • 31. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public31 Summary  Bi-directional full-duplex communication on the web – Chat, online multiplayer games, collaboration, real time monitoring  Java API for WebSocket standardized as part of Java EE 7 – Interface-driven – Annotation-driven  Client and server APIs  Supported by major server-side Java platforms
  • 32. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public32 Learning More  Specification – JSR: jcp.org/en/jsr/detail?id=356 – Mailing Lists, JIRA, Archive: java.net/projects/websocket-spec  Reference Implementation – Tyrus: java.net/projects/tyrus – GlassFish: http://glassfish.org  Dig Deeper – Java EE Tutorial: http://docs.oracle.com/javaee/7/tutorial/doc/websocket.htm – Java EE 7 Hands-on-Lab: https://glassfish.java.net/hol/ – Cargo Tracker Java EE Blue Prints Project: https://java.net/projects/cargotracker/
  • 33. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public33