SlideShare a Scribd company logo
JSR 356: Building HTML5
WebSocket Apps in Java
Arun Gupta
Java EE & GlassFish Guy
blogs.oracle.com/arungupta, @arungupta




1   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
The preceding is intended to outline our general product direction. It is intended
        for information purposes only, and may not be incorporated into any contract.
        It is not a commitment to deliver any material, code, or functionality, and should
        not be relied upon in making purchasing decisions. The development, release,
        and timing of any features or functionality described for Oracle s products
        remains at the sole discretion of Oracle.




2   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Agenda


        §  Primer on WebSocket


        §  JSR 356: Java API for WebSocket




3   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Interactive Web Sites


         §  HTTP is half-duplex
         §  HTTP is verbose
         §  Hacks for Server Push
                    –  Polling
                    –  Long Polling
                    –  Comet/Ajax
         §  Complex, Inefficient, Wasteful



4   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
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 © 2012, Oracle and/or its affiliates. All rights reserved.
What’s the basic idea ?


         §  Upgrade HTTP to upgrade to WebSocket
                    –  Single TCP connection
                    –  Transparent to proxies, firewalls, and routers
         §  Send data frames in both direction (Bi-directional)
                    –  No headers, cookies, authentication
                    –  No security overhead
                    –  “ping”/”pong” frames for keep-alive
         §  Send message independent of each other (Full Duplex)
         §  End the connection
6   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Establish a connection


                                                                            Handshake Request



                     Client                                                                     Server
                                                                           Handshake Response




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


         HTTP/1.1 101 Switching Protocols

         Upgrade: websocket

         Connection: Upgrade

         Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

         Sec-WebSocket-Protocol: chat "




9   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Establishing a Connection


                                                                             Handshake Request



                      Client                                                                     Server
                                                                            Handshake Response




                                                                                Connected !


10   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
WebSocket Lifecycle
                                                                            Connected !

                                                                 open                      open


                                                       message
                                                                                           message
                                                            message
                                                       message
                      Client                                                               error     Server


                                                                                           message

                                                                 close


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




12   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java WebSocket Implementations
                                          Java-WebSocket                    Kaazing WebSocket Gateway
                                                        Grizzly                  WebSocket SDK
                                         Apache Tomcat 7                             Webbit
                                                    GlassFish                      Atmosphere
                                                    Autobahn                      websockets4j
                                              WeberKnecht                       GNU WebSocket4J
                                                           Jetty                      Netty
                                                         JBoss                     TorqueBox
                                              Caucho Resin                       SwaggerSocket
                                                 jWebSocket                          jWamp

13   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Browser Support




14   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   http://caniuse.com/websockets
JSR 356 Specification


          §  Standard API for creating WebSocket Applications
          §  Transparent Expert Group
                     –  jcp.org/en/jsr/detail?id=356
                     –  java.net/projects/websocket-spec
          §  Now: Early Draft Review
          §  December: Public Draft Review
          §  Will be in Java EE 7
                     –  Under discussion: Client API in Java SE


15   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
JSR 356: Reference Implementation


          §  Tyrus: java.net/projects/tyrus
          §  Originated as WebSocket SDK
                     –  java.net/projects/websocket-sdk
          §  Pluggable Protocol Provider
                     –  Default is Grizzly/GlassFish
                     –  Portable to WebLogic
          §  Integrated in GlassFish 4 Builds



16   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
JSR 356 Expert Group
                                         Jean-Francois Arcand                     Individual
                                                Scott Ferguson              Caucho Technology, Inc
                                                    Joe Walnes               DRW Holdings, LLC
                                                 Minehiko IIDA                  Fujitsu Limited
                                                    Wenbo Zhu                    Google Inc.
                                                     Bill Wigger                     IBM
                                                     Justin Lee                   Individual
                                                Danny Coward                        Oracle
                                              Rémy Maucherat                       RedHat
                                              Moon Namkoong                     TmaxSoft, Inc.
                                                 Mark Thomas                       VMware
                                                      Wei Chen                Voxeo Corporation
                                                  Greg Wilkins                    Individual

17   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket Features


          §  Create WebSocket Client/Endpoints
                     –  Annotation-driven (@WebSocketEndpoint)
                     –  Interface-driven (Endpoint)
          §  SPI for extensions and data frames
          §  Integration with Java EE Web container




18   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Touring the APIs




19   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Note: The APIs might change
                                                           before final release !




20   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Hello World and Basics
                                                                              POJO




21   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Hello World

      import javax.net.websocket.annotations.*;

      

      @WebSocketEndpoint("/hello")

      public class HelloBean {

      

                       @WebSocketMessage

                       public String sayHello(String name) {

                           return “Hello “ + name;

                       }

      }"




22   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
WebSocket Annotations

                                    Annotation                               Level                        Purpose

            @WebSocketEndpoint"                                               class   Turns a POJO into a WebSocket Endpoint

            @WebSocketOpen"                                                  method   Intercepts WebSocket Open events

            @WebSocketClose"                                                 method   Intercepts WebSocket Close events

            @WebSocketMessage"                                               method   Intercepts WebSocket Message events

                                                                             method
            @WebSocketPathParam"                                                      Flags a matched path segment of a URI-template
                                                                            parameter

            @WebSocketError"                                                 method   Intercepts errors during a conversation


23   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
@WebSocketEndpoint attributes



                                                                                    Relative URI or URI template
                                    value"                                     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




24   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Custom Payloads


          @WebSocketEndpoint(

              value="/hello",

              encoders={MyMessage.class},

              decoders={MyMessage.class}

          )

          public class MyEndpoint {

              . . .

          }"
          "
          "
25   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Custom Payloads – Text

          public class MyMessage implements Decoder.Text<MyMessage>,
          Encoder.Text<MyMessage> {

            private JsonObject jsonObject;

          

                 public MyMessage decode(String s) {

                   jsonObject = new JsonReader(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();

                 }

          }"
26   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
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) {

                    . . .

                 }

          }"
27   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Chat Sample


          @WebSocketEndpoint("/chat")"
          public class ChatBean {"
                        Set<Session> peers = Collections.synchronizedSet(…);

          

                        @WebSocketOpen

                        public void onOpen(Session peer) {

                            peers.add(peer);

                        }

          

                        @WebSocketClose

                        public void onClose(Session peer) {

                            peers.remove(peer);

                        }

          

                        . . ."
28   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Chat Sample


                        . . .

          

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

                                         peer.getRemote().sendObject(message);

                                     }

                        }

          }"




29   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
URI Template Matching


          §  Level 1 only


            @WebSocketEndpoint(“/orders/{order-id}”)

            public class MyEndpoint {

              @WebSocketMessage

              public void processOrder(

                 @WebSocketPathParam(“order-id”)String orderId) {

                 . . .

              }

            }

30   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Which methods can be @WebSocketMessage ?


          §  A parameter type that can be decoded in incoming message
                     –  String, byte[], ByteBuffer or any type for which there is a decoder
          §  An optional Session parameter
          §  0..n String parameters annotated with
              @WebSocketPathParameter"
          §  A return type that can be encoded in outgoing message
                     –  String, byte[], ByteBuffer or any type for which there is a encoder




31   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
WebSocket Subprotocols


          §  Facilitates application layer protocols
          §  Registered in a Subprotocol Name Registry
                     –  Identifier, Common name, Definition
                     –  www.iana.org/assignments/websocket/websocket.xml#subprotocol-name

          §  4 officially registered
                     –  Message Broker (2 versions)
                     –  SOAP
                     –  WebSocket Application Messaging Protocol (WAMP)
                                  §  RPC, PubSub
32   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Packaging – Java EE Style

        §  Client side
             §  Classes + resources packaged as a JAR


        §  Web Container
                     §  Classes + resources packaged in a WAR file




33   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Hello World and Basics
                                                                            Non-POJO




34   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Hello World Server
     import javax.net.websocket.*;"
     "
     public class HelloServer extends Endpoint {

        @Override

        public void onOpen(Session session) {

           session.addMessageHandler(new MessageHandler.Text() {

             public void onMessage(String name) {

                try {

                   session.getRemote().sendString(“Hello “ + name);

                } catch (IOException ex) {

                }

             }          

           });

        }

     }"
35   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Server Configuration - Bootstrap

     URI serverURI = new URI("/hello");

     ServerContainer serverContainer = 

         ContainerProvider.getServerContainer();

     Endpoint helloServer = new HelloServer();

     ServerEndpointConfiguration serverConfig = 

         new DefaultServerConfiguration(serverURI);

     serverContainer.publishServer(helloServer, serverConfig);"




     Recommended in ServletContextListener                                  *"


36   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Hello World Client

     import javax.net.websocket.*;"
     "
     public class HelloClient extends Endpoint {

        @Override

        public void onOpen(Session session) {

           try {

              session.getRemote().sendString("Hello you !");

           } catch (IOException ioe) {

              // . . .        

           }

        }

     }"

37   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Server and Client Configuration


          §  Server
                     –  URI matching algorithm
                     –  Subprotocol and extension negotiation
                     –  Message encoders and decoders
                     –  Origin check
                     –  Handshake response
          §  Client
                     –  Requested subprotocols and extensions
                     –  Message encoders and decoders

38
                     –  Request URI
     Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Main API Classes: javax.net.websocket.*


          §  Endpoint: Intercepts WebSocket lifecycle events


          §  MessageHandler: Handles all incoming messages for an Endpoint


          §  RemoteEndpoint: Represents the ‘other end’ of this conversation


          §  Session: Represents the active conversation




39   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Sending the Message
Whole string *                                             RemoteEndpoint"      sendString(String message)"

Binary data *                                              RemoteEndpoint"      sendString(ByteBuffer message)"

String fragments                                           RemoteEndpoint"      sendPartialString(String part, boolean last)"

                                                                                sendPartialData(ByteBuffer part, boolean
Binary data fragments                                      RemoteEndpoint"
                                                                                last)"

Blocking stream of text                                    RemoteEndpoint"      Writer getSendWriter())"

Blocking stream of binary
                          RemoteEndpoint"                                       OutputStream getSendStream()"
data

Custom object of type T * RemoteEndpoint<T>" sendObject(T customObject)"

                                                                               * additional flavors: by completion, by future
   40   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Receiving the Message
Whole string                                          MessageHandler.Text"            onMessage(String message)"

Binary data                                           MessageHandler.Binary"          onMessage(ByteBuffer message)"

                                                                                      onMessage(String part, boolean
String fragments                                      MessageHandler.AsyncText"
                                                                                      last)"
                                                                                      onMessage(ByteBuffer part,
Binary data fragments                                 MessageHandler.AsyncBinary"
                                                                                      boolean last)"

Blocking stream of text                               MessageHandler.CharacterStream" onMessage(Reader r)"

Blocking stream of
                                                      MessageHandler.BinaryStream"    onMessage(InputStream r)"
binary data

Custom object of type T MessageHandler.DecodedObject<T>" onMessage(T customObject)"


   41   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Relationship with Servlet 3.1


          §  Allows a portable way to upgrade HTTP request
          §  New API
                     –  HttpServletRequest.upgrade(ProtocolHandler
                            handler)"




42   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Security


          §  Authenticates using Servlet security mechanism during opening
                handshake
                     –  Endpoint mapped by ws:// is protected using security model defined
                            using the corresponding http:// URI
          §  Authorization defined using <security-constraint>"
                     –  TBD: Add/reuse security annotations
          §  Transport Confidentiality using wss://"
                     –  Access allowed over encrypted connection only



43   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
API TODO
         Lots …


          §  Refactoring/renaming
                     –  Class naming, fluency
                     –  Collapse MessageHandlers
                     –  Re-org/rename annotations
          Use of @WebSocketEndpoint on Endpoint instead of
          ServerConfiguration API
          §  More knobs and dials on POJO
          §  Exception handling
          §  Integration with Java EE
44   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
How to view WebSocket messages ?
         Capture traffic on loopback




45   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
How to view WebSocket messages ?
         chrome://net-internals -> Sockets -> View live sockets




46   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Resources


          §  Specification
                     –  JSR: jcp.org/en/jsr/detail?id=356
                     –  Mailing Lists, JIRA, Archive: java.net/projects/websocket-spec
                     –  Now: Early Draft Review
                     –  Will be in Java EE 7
          §  Reference Implementation
                     –  Tyrus: java.net/projects/tyrus
                     –  Now: Integrated in GlassFish 4 builds


47   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Q&A



48   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Graphic Section Divider




49   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
50   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Ad

Recommended

Java Summit Chennai: JAX-RS 2.0
Java Summit Chennai: JAX-RS 2.0
Arun Gupta
 
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
Arun Gupta
 
Running your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the Cloud
Arun Gupta
 
GlassFish & Java EE Business Update @ CEJUG
GlassFish & Java EE Business Update @ CEJUG
Arun Gupta
 
Getting Started with Rails on GlassFish (Hands-on Lab) - Spark IT 2010
Getting Started with Rails on GlassFish (Hands-on Lab) - Spark IT 2010
Arun Gupta
 
Powering the Next Generation Services with Java Platform - Spark IT 2010
Powering the Next Generation Services with Java Platform - Spark IT 2010
Arun Gupta
 
Running your Java EE 6 applications in the Cloud @ Silicon Valley Code Camp 2010
Running your Java EE 6 applications in the Cloud @ Silicon Valley Code Camp 2010
Arun Gupta
 
The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011
Arun Gupta
 
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
Arun Gupta
 
Running your Java EE applications in the Cloud
Running your Java EE applications in the Cloud
Arun Gupta
 
5050 dev nation
5050 dev nation
Arun Gupta
 
GlassFish REST Administration Backend
GlassFish REST Administration Backend
Arun Gupta
 
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
Arun Gupta
 
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
Arun Gupta
 
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Arun Gupta
 
GIDS 2012: PaaSing a Java EE Application
GIDS 2012: PaaSing a Java EE Application
Arun Gupta
 
Java EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for future
Arun Gupta
 
GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0
Arun Gupta
 
The Java EE 7 Platform: Developing for the Cloud (FISL 12)
The Java EE 7 Platform: Developing for the Cloud (FISL 12)
Arun Gupta
 
GlassFish 3.1 at JCertif 2011
GlassFish 3.1 at JCertif 2011
Arun Gupta
 
Creating Quick and Powerful Web applications with Oracle, GlassFish and NetBe...
Creating Quick and Powerful Web applications with Oracle, GlassFish and NetBe...
Arun Gupta
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5
Arun Gupta
 
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Skills Matter
 
WebLogic 12c Developer Deep Dive at Oracle Develop India 2012
WebLogic 12c Developer Deep Dive at Oracle Develop India 2012
Arun Gupta
 
Java EE 7 overview
Java EE 7 overview
Masoud Kalali
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)
Pavel Bucek
 
Java EE 6 = Less Code + More Power
Java EE 6 = Less Code + More Power
Arun Gupta
 
Understanding
Understanding
Arun Gupta
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun Gupta
JAX London
 
Websocket 1.0
Websocket 1.0
Arun Gupta
 

More Related Content

What's hot (20)

OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
Arun Gupta
 
Running your Java EE applications in the Cloud
Running your Java EE applications in the Cloud
Arun Gupta
 
5050 dev nation
5050 dev nation
Arun Gupta
 
GlassFish REST Administration Backend
GlassFish REST Administration Backend
Arun Gupta
 
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
Arun Gupta
 
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
Arun Gupta
 
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Arun Gupta
 
GIDS 2012: PaaSing a Java EE Application
GIDS 2012: PaaSing a Java EE Application
Arun Gupta
 
Java EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for future
Arun Gupta
 
GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0
Arun Gupta
 
The Java EE 7 Platform: Developing for the Cloud (FISL 12)
The Java EE 7 Platform: Developing for the Cloud (FISL 12)
Arun Gupta
 
GlassFish 3.1 at JCertif 2011
GlassFish 3.1 at JCertif 2011
Arun Gupta
 
Creating Quick and Powerful Web applications with Oracle, GlassFish and NetBe...
Creating Quick and Powerful Web applications with Oracle, GlassFish and NetBe...
Arun Gupta
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5
Arun Gupta
 
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Skills Matter
 
WebLogic 12c Developer Deep Dive at Oracle Develop India 2012
WebLogic 12c Developer Deep Dive at Oracle Develop India 2012
Arun Gupta
 
Java EE 7 overview
Java EE 7 overview
Masoud Kalali
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)
Pavel Bucek
 
Java EE 6 = Less Code + More Power
Java EE 6 = Less Code + More Power
Arun Gupta
 
Understanding
Understanding
Arun Gupta
 
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
Arun Gupta
 
Running your Java EE applications in the Cloud
Running your Java EE applications in the Cloud
Arun Gupta
 
5050 dev nation
5050 dev nation
Arun Gupta
 
GlassFish REST Administration Backend
GlassFish REST Administration Backend
Arun Gupta
 
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
Arun Gupta
 
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
Arun Gupta
 
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Arun Gupta
 
GIDS 2012: PaaSing a Java EE Application
GIDS 2012: PaaSing a Java EE Application
Arun Gupta
 
Java EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for future
Arun Gupta
 
GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0
Arun Gupta
 
The Java EE 7 Platform: Developing for the Cloud (FISL 12)
The Java EE 7 Platform: Developing for the Cloud (FISL 12)
Arun Gupta
 
GlassFish 3.1 at JCertif 2011
GlassFish 3.1 at JCertif 2011
Arun Gupta
 
Creating Quick and Powerful Web applications with Oracle, GlassFish and NetBe...
Creating Quick and Powerful Web applications with Oracle, GlassFish and NetBe...
Arun Gupta
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5
Arun Gupta
 
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Skills Matter
 
WebLogic 12c Developer Deep Dive at Oracle Develop India 2012
WebLogic 12c Developer Deep Dive at Oracle Develop India 2012
Arun Gupta
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)
Pavel Bucek
 
Java EE 6 = Less Code + More Power
Java EE 6 = Less Code + More Power
Arun Gupta
 
Understanding
Understanding
Arun Gupta
 

Similar to Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012 (20)

HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun Gupta
JAX London
 
Websocket 1.0
Websocket 1.0
Arun Gupta
 
Pushing the web — WebSockets
Pushing the web — WebSockets
Roland M
 
Building WebSocket and Server Side Events Applications using Atmosphere
Building WebSocket and Server Side Events Applications using Atmosphere
jfarcand
 
Introduction to WebSockets
Introduction to WebSockets
Gunnar Hillert
 
Writing Portable WebSockets in Java
Writing Portable WebSockets in Java
jfarcand
 
WebSocket
WebSocket
njamnjam
 
Ws
Ws
Sunghan Kim
 
Programming WebSockets with Glassfish and Grizzly
Programming WebSockets with Glassfish and Grizzly
C2B2 Consulting
 
The HTML5 WebSocket API
The HTML5 WebSocket API
David Lindkvist
 
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011
Peter Moskovits
 
WebSockets in JEE 7
WebSockets in JEE 7
Shahzad Badar
 
WebSocket protocol
WebSocket protocol
Kensaku Komatsu
 
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
 
DevCon 5 (July 2013) - WebSockets
DevCon 5 (July 2013) - WebSockets
Crocodile WebRTC SDK and Cloud Signalling Network
 
Codecamp Iasi-26 nov 2011 - Html 5 WebSockets
Codecamp Iasi-26 nov 2011 - Html 5 WebSockets
Florin Cardasim
 
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
Charles Moulliard
 
Codecamp iasi-26 nov 2011-web sockets
Codecamp iasi-26 nov 2011-web sockets
Codecamp Romania
 
WebSocket in Enterprise Applications 2015
WebSocket in Enterprise Applications 2015
Pavel Bucek
 
Real time websites and mobile apps with SignalR
Real time websites and mobile apps with SignalR
Roy Cornelissen
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun Gupta
JAX London
 
Pushing the web — WebSockets
Pushing the web — WebSockets
Roland M
 
Building WebSocket and Server Side Events Applications using Atmosphere
Building WebSocket and Server Side Events Applications using Atmosphere
jfarcand
 
Introduction to WebSockets
Introduction to WebSockets
Gunnar Hillert
 
Writing Portable WebSockets in Java
Writing Portable WebSockets in Java
jfarcand
 
Programming WebSockets with Glassfish and Grizzly
Programming WebSockets with Glassfish and Grizzly
C2B2 Consulting
 
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011
Peter Moskovits
 
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
 
Codecamp Iasi-26 nov 2011 - Html 5 WebSockets
Codecamp Iasi-26 nov 2011 - Html 5 WebSockets
Florin Cardasim
 
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
Charles Moulliard
 
Codecamp iasi-26 nov 2011-web sockets
Codecamp iasi-26 nov 2011-web sockets
Codecamp Romania
 
WebSocket in Enterprise Applications 2015
WebSocket in Enterprise Applications 2015
Pavel Bucek
 
Real time websites and mobile apps with SignalR
Real time websites and mobile apps with SignalR
Roy Cornelissen
 
Ad

More from Arun Gupta (20)

5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf
Arun Gupta
 
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019
Arun Gupta
 
Machine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and Kubernetes
Arun Gupta
 
Secure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using Firecracker
Arun Gupta
 
Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019
Arun Gupta
 
Why Amazon Cares about Open Source
Why Amazon Cares about Open Source
Arun Gupta
 
Machine learning using Kubernetes
Machine learning using Kubernetes
Arun Gupta
 
Building Cloud Native Applications
Building Cloud Native Applications
Arun Gupta
 
Chaos Engineering with Kubernetes
Chaos Engineering with Kubernetes
Arun Gupta
 
How to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAM
Arun Gupta
 
Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018
Arun Gupta
 
The Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 Keynote
Arun Gupta
 
Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018
Arun Gupta
 
Mastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv Summit
Arun Gupta
 
Top 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's Landscape
Arun Gupta
 
Container Landscape in 2017
Container Landscape in 2017
Arun Gupta
 
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Arun Gupta
 
Docker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developers
Arun Gupta
 
Thanks Managers!
Thanks Managers!
Arun Gupta
 
Migrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to Containers
Arun Gupta
 
5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf
Arun Gupta
 
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019
Arun Gupta
 
Machine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and Kubernetes
Arun Gupta
 
Secure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using Firecracker
Arun Gupta
 
Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019
Arun Gupta
 
Why Amazon Cares about Open Source
Why Amazon Cares about Open Source
Arun Gupta
 
Machine learning using Kubernetes
Machine learning using Kubernetes
Arun Gupta
 
Building Cloud Native Applications
Building Cloud Native Applications
Arun Gupta
 
Chaos Engineering with Kubernetes
Chaos Engineering with Kubernetes
Arun Gupta
 
How to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAM
Arun Gupta
 
Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018
Arun Gupta
 
The Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 Keynote
Arun Gupta
 
Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018
Arun Gupta
 
Mastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv Summit
Arun Gupta
 
Top 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's Landscape
Arun Gupta
 
Container Landscape in 2017
Container Landscape in 2017
Arun Gupta
 
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Arun Gupta
 
Docker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developers
Arun Gupta
 
Thanks Managers!
Thanks Managers!
Arun Gupta
 
Migrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to Containers
Arun Gupta
 
Ad

Recently uploaded (20)

OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
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
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
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
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 

Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012

  • 1. JSR 356: Building HTML5 WebSocket Apps in Java Arun Gupta Java EE & GlassFish Guy blogs.oracle.com/arungupta, @arungupta 1 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 2. The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle s products remains at the sole discretion of Oracle. 2 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 3. Agenda §  Primer on WebSocket §  JSR 356: Java API for WebSocket 3 Copyright © 2012, 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 4 Copyright © 2012, 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 5 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 6. What’s the basic idea ? §  Upgrade HTTP to upgrade to WebSocket –  Single TCP connection –  Transparent to proxies, firewalls, and routers §  Send data frames in both direction (Bi-directional) –  No headers, cookies, authentication –  No security overhead –  “ping”/”pong” frames for keep-alive §  Send message independent of each other (Full Duplex) §  End the connection 6 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 7. Establish a connection Handshake Request Client Server Handshake Response 7 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 8. 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 © 2012, Oracle and/or its affiliates. All rights reserved.
  • 9. Handshake Response HTTP/1.1 101 Switching Protocols
 Upgrade: websocket
 Connection: Upgrade
 Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 Sec-WebSocket-Protocol: chat " 9 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 10. Establishing a Connection Handshake Request Client Server Handshake Response Connected ! 10 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 11. WebSocket Lifecycle Connected ! open open message message message message Client error Server message close Disconnected 11 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 12. WebSocket API www.w3.org/TR/websockets/ 12 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 13. Java WebSocket Implementations Java-WebSocket Kaazing WebSocket Gateway Grizzly WebSocket SDK Apache Tomcat 7 Webbit GlassFish Atmosphere Autobahn websockets4j WeberKnecht GNU WebSocket4J Jetty Netty JBoss TorqueBox Caucho Resin SwaggerSocket jWebSocket jWamp 13 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 14. Browser Support 14 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. http://caniuse.com/websockets
  • 15. JSR 356 Specification §  Standard API for creating WebSocket Applications §  Transparent Expert Group –  jcp.org/en/jsr/detail?id=356 –  java.net/projects/websocket-spec §  Now: Early Draft Review §  December: Public Draft Review §  Will be in Java EE 7 –  Under discussion: Client API in Java SE 15 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 16. JSR 356: Reference Implementation §  Tyrus: java.net/projects/tyrus §  Originated as WebSocket SDK –  java.net/projects/websocket-sdk §  Pluggable Protocol Provider –  Default is Grizzly/GlassFish –  Portable to WebLogic §  Integrated in GlassFish 4 Builds 16 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 17. JSR 356 Expert Group Jean-Francois Arcand Individual Scott Ferguson Caucho Technology, Inc Joe Walnes DRW Holdings, LLC Minehiko IIDA Fujitsu Limited Wenbo Zhu Google Inc. Bill Wigger IBM Justin Lee Individual Danny Coward Oracle Rémy Maucherat RedHat Moon Namkoong TmaxSoft, Inc. Mark Thomas VMware Wei Chen Voxeo Corporation Greg Wilkins Individual 17 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 18. Java API for WebSocket Features §  Create WebSocket Client/Endpoints –  Annotation-driven (@WebSocketEndpoint) –  Interface-driven (Endpoint) §  SPI for extensions and data frames §  Integration with Java EE Web container 18 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 19. Touring the APIs 19 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 20. Note: The APIs might change before final release ! 20 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 21. Hello World and Basics POJO 21 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 22. Hello World import javax.net.websocket.annotations.*;
 
 @WebSocketEndpoint("/hello")
 public class HelloBean {
 
 @WebSocketMessage
 public String sayHello(String name) {
 return “Hello “ + name;
 }
 }" 22 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 23. WebSocket Annotations Annotation Level Purpose @WebSocketEndpoint" class Turns a POJO into a WebSocket Endpoint @WebSocketOpen" method Intercepts WebSocket Open events @WebSocketClose" method Intercepts WebSocket Close events @WebSocketMessage" method Intercepts WebSocket Message events method @WebSocketPathParam" Flags a matched path segment of a URI-template parameter @WebSocketError" method Intercepts errors during a conversation 23 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 24. @WebSocketEndpoint attributes Relative URI or URI template value" 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 24 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 25. Custom Payloads @WebSocketEndpoint(
 value="/hello",
 encoders={MyMessage.class},
 decoders={MyMessage.class}
 )
 public class MyEndpoint {
 . . .
 }" " " 25 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 26. Custom Payloads – Text public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> {
 private JsonObject jsonObject;
 
 public MyMessage decode(String s) {
 jsonObject = new JsonReader(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();
 }
 }" 26 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 27. 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) {
 . . .
 }
 }" 27 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 28. Chat Sample @WebSocketEndpoint("/chat")" public class ChatBean {" Set<Session> peers = Collections.synchronizedSet(…);
 
 @WebSocketOpen
 public void onOpen(Session peer) {
 peers.add(peer);
 }
 
 @WebSocketClose
 public void onClose(Session peer) {
 peers.remove(peer);
 }
 
 . . ." 28 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 29. Chat Sample . . .
 
 @WebSocketMessage" public void message(String message, Session client) {" for (Session peer : peers) {
 peer.getRemote().sendObject(message);
 }
 }
 }" 29 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 30. URI Template Matching §  Level 1 only @WebSocketEndpoint(“/orders/{order-id}”)
 public class MyEndpoint {
 @WebSocketMessage
 public void processOrder(
 @WebSocketPathParam(“order-id”)String orderId) {
 . . .
 }
 } 30 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 31. Which methods can be @WebSocketMessage ? §  A parameter type that can be decoded in incoming message –  String, byte[], ByteBuffer or any type for which there is a decoder §  An optional Session parameter §  0..n String parameters annotated with @WebSocketPathParameter" §  A return type that can be encoded in outgoing message –  String, byte[], ByteBuffer or any type for which there is a encoder 31 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 32. WebSocket Subprotocols §  Facilitates application layer protocols §  Registered in a Subprotocol Name Registry –  Identifier, Common name, Definition –  www.iana.org/assignments/websocket/websocket.xml#subprotocol-name §  4 officially registered –  Message Broker (2 versions) –  SOAP –  WebSocket Application Messaging Protocol (WAMP) §  RPC, PubSub 32 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 33. Packaging – Java EE Style §  Client side §  Classes + resources packaged as a JAR §  Web Container §  Classes + resources packaged in a WAR file 33 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 34. Hello World and Basics Non-POJO 34 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 35. Hello World Server import javax.net.websocket.*;" " public class HelloServer extends Endpoint {
 @Override
 public void onOpen(Session session) {
 session.addMessageHandler(new MessageHandler.Text() {
 public void onMessage(String name) {
 try {
 session.getRemote().sendString(“Hello “ + name);
 } catch (IOException ex) {
 }
 } 
 });
 }
 }" 35 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 36. Server Configuration - Bootstrap URI serverURI = new URI("/hello");
 ServerContainer serverContainer = 
 ContainerProvider.getServerContainer();
 Endpoint helloServer = new HelloServer();
 ServerEndpointConfiguration serverConfig = 
 new DefaultServerConfiguration(serverURI);
 serverContainer.publishServer(helloServer, serverConfig);" Recommended in ServletContextListener *" 36 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 37. Hello World Client import javax.net.websocket.*;" " public class HelloClient extends Endpoint {
 @Override
 public void onOpen(Session session) {
 try {
 session.getRemote().sendString("Hello you !");
 } catch (IOException ioe) {
 // . . . 
 }
 }
 }" 37 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 38. Server and Client Configuration §  Server –  URI matching algorithm –  Subprotocol and extension negotiation –  Message encoders and decoders –  Origin check –  Handshake response §  Client –  Requested subprotocols and extensions –  Message encoders and decoders 38 –  Request URI Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 39. Main API Classes: javax.net.websocket.* §  Endpoint: Intercepts WebSocket lifecycle events §  MessageHandler: Handles all incoming messages for an Endpoint §  RemoteEndpoint: Represents the ‘other end’ of this conversation §  Session: Represents the active conversation 39 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 40. Sending the Message Whole string * RemoteEndpoint" sendString(String message)" Binary data * RemoteEndpoint" sendString(ByteBuffer message)" String fragments RemoteEndpoint" sendPartialString(String part, boolean last)" sendPartialData(ByteBuffer part, boolean Binary data fragments RemoteEndpoint" last)" Blocking stream of text RemoteEndpoint" Writer getSendWriter())" Blocking stream of binary RemoteEndpoint" OutputStream getSendStream()" data Custom object of type T * RemoteEndpoint<T>" sendObject(T customObject)" * additional flavors: by completion, by future 40 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 41. Receiving the Message Whole string MessageHandler.Text" onMessage(String message)" Binary data MessageHandler.Binary" onMessage(ByteBuffer message)" onMessage(String part, boolean String fragments MessageHandler.AsyncText" last)" onMessage(ByteBuffer part, Binary data fragments MessageHandler.AsyncBinary" boolean last)" Blocking stream of text MessageHandler.CharacterStream" onMessage(Reader r)" Blocking stream of MessageHandler.BinaryStream" onMessage(InputStream r)" binary data Custom object of type T MessageHandler.DecodedObject<T>" onMessage(T customObject)" 41 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 42. Relationship with Servlet 3.1 §  Allows a portable way to upgrade HTTP request §  New API –  HttpServletRequest.upgrade(ProtocolHandler handler)" 42 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 43. Security §  Authenticates using Servlet security mechanism during opening handshake –  Endpoint mapped by ws:// is protected using security model defined using the corresponding http:// URI §  Authorization defined using <security-constraint>" –  TBD: Add/reuse security annotations §  Transport Confidentiality using wss://" –  Access allowed over encrypted connection only 43 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 44. API TODO Lots … §  Refactoring/renaming –  Class naming, fluency –  Collapse MessageHandlers –  Re-org/rename annotations Use of @WebSocketEndpoint on Endpoint instead of ServerConfiguration API §  More knobs and dials on POJO §  Exception handling §  Integration with Java EE 44 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 45. How to view WebSocket messages ? Capture traffic on loopback 45 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 46. How to view WebSocket messages ? chrome://net-internals -> Sockets -> View live sockets 46 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 47. Resources §  Specification –  JSR: jcp.org/en/jsr/detail?id=356 –  Mailing Lists, JIRA, Archive: java.net/projects/websocket-spec –  Now: Early Draft Review –  Will be in Java EE 7 §  Reference Implementation –  Tyrus: java.net/projects/tyrus –  Now: Integrated in GlassFish 4 builds 47 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 48. Q&A 48 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 49. Graphic Section Divider 49 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 50. 50 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.