SlideShare ist ein Scribd-Unternehmen logo
1 von 57
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
         !  Flavors of 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 ?


         !  Establish a connection (Single TCP connection)
         !  Send messages in both direction (Bi-directional)
         !  Send message independent of each other (Full Duplex)
         !  End the connection




6   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
What does it add over TCP ?


         !  Origin-based security model for browsers
         !  Adds an addressing and protocol naming mechanism to support
            multiple services on one port
         !  Layers a framing mechanism on top of TCP
         !  Includes an additional in-band closing handshake




7   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Establish a connection


                                                                            Handshake Request



                     Client                                                                     Server
                                                                           Handshake Response




8   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 "



9   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 "




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


                                                                             Handshake Request



                      Client                                                                     Server
                                                                            Handshake Response




                                                                                Connected !


11   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
12   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
WebSocket API
         www.w3.org/TR/websockets/




13   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

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




15   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


16   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



17   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

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


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




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




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




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




22   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;

                       }

      }"




23   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


24   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




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


          @WebSocketEndpoint(

              path="/hello",

              encoders={MyMessage.class},

              decoders={MyMessage.class}

          )

          public class MyEndpoint {

              . . .

          }"
          "
          "
26   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();

                 }

          }"
27   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) {

                    . . .

                 }

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


          @WebSocketEndpoint(path="/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);

                        }

          

                        . . ."
29   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);

                                     }

                        }

          }"




30   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) {

                 . . .

              }

            }

31   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[] 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[] or any type for which there is a decoder




32   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
33   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
WebSocket Subprotocols
         TBD




34   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
WebSocket Extensions


          !  Add capabilities to the base protocol
                     –  Endpoints negotiate during opening handshake
                     –  “Formal” or Private (prefixed with “x-”)
          !  Multiplexing
                     –  http://tools.ietf.org/html/draft-tamplin-hybi-google-mux
          !  Compression: Only non-control frames/messages
                     –  Per-frame:
                            http://tools.ietf.org/html/draft-tyoshino-hybi-websocket-perframe-deflate
                     –  Per-message:
                            http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression
35   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
WebSocket Extensions
         Early Work . . .


          !  Extension.createIncomingFrameHandler,
                createOutgoingFrameHandler"
          !  Added to EndpointConfiguration"




36   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




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




38   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) {

                }

             }          

           });

        }

     }"
39   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                                  *"


40   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) {

              // . . .        

           }

        }

     }"

41   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

42
                     –  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




43   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Object Model
                                                                                                 Message
                                   Remote                                                        Handler
                                   Endpoint
     Client                                                                            Session




                                                                                                            WebSocket
                                                                                                             Endpoint
                                                                                                 Message
                                   Remote                                                        Handler
                                   Endpoint
     Client                                                                 Internet   Session

                                                                                                  Message
                                                                                                  Handler
                                      Remote

     Client
                                      Endpoint
                                                                                       Session

44   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
   45   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)"


   46   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)"




47   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



48   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Advanced Features


          !  DataFrame SPI
          !  Integration with Java EE and Web Applications
                     –  Injectable components




49   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
50   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
How to view WebSocket messages ?
         Capture traffic on loopback




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




52   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
WebSocket Future ???


          !  Protocol Updates
          !  HTTP 2.0
          !  SPDY




53   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


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



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




56   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
57   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Weitere ähnliche Inhalte

Was ist angesagt?

OSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worldsOSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worldsArun Gupta
 
JSF 2.2 Input Output JavaLand 2015
JSF 2.2 Input Output JavaLand 2015JSF 2.2 Input Output JavaLand 2015
JSF 2.2 Input Output JavaLand 2015Edward Burns
 
MySQL Connector/J Feature Review and How to Upgrade from Connector/J 5.1
MySQL Connector/J Feature Review and How to Upgrade from Connector/J 5.1MySQL Connector/J Feature Review and How to Upgrade from Connector/J 5.1
MySQL Connector/J Feature Review and How to Upgrade from Connector/J 5.1Filipe Silva
 
OpenStack Summit Portland April 2013 talk - Quantum and EC2
OpenStack Summit Portland April 2013 talk - Quantum and EC2OpenStack Summit Portland April 2013 talk - Quantum and EC2
OpenStack Summit Portland April 2013 talk - Quantum and EC2Naveen Joy
 
OSGi Community Event 2010 - Enterprise OSGi in WebSphere and Apache Aries
OSGi Community Event 2010 - Enterprise OSGi in WebSphere and Apache AriesOSGi Community Event 2010 - Enterprise OSGi in WebSphere and Apache Aries
OSGi Community Event 2010 - Enterprise OSGi in WebSphere and Apache Ariesmfrancis
 
Open Admin - GWT
Open Admin - GWTOpen Admin - GWT
Open Admin - GWTCredera
 
Comet and the Rise of Highly Interactive Websites
Comet and the Rise of Highly Interactive WebsitesComet and the Rise of Highly Interactive Websites
Comet and the Rise of Highly Interactive WebsitesJoe Walker
 
Ed presents JSF 2.2 at a 2013 Gameduell Tech talk
Ed presents JSF 2.2 at a 2013 Gameduell Tech talkEd presents JSF 2.2 at a 2013 Gameduell Tech talk
Ed presents JSF 2.2 at a 2013 Gameduell Tech talkEdward Burns
 
GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0Arun Gupta
 

Was ist angesagt? (10)

OSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worldsOSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worlds
 
JSF 2.2 Input Output JavaLand 2015
JSF 2.2 Input Output JavaLand 2015JSF 2.2 Input Output JavaLand 2015
JSF 2.2 Input Output JavaLand 2015
 
MySQL Connector/J Feature Review and How to Upgrade from Connector/J 5.1
MySQL Connector/J Feature Review and How to Upgrade from Connector/J 5.1MySQL Connector/J Feature Review and How to Upgrade from Connector/J 5.1
MySQL Connector/J Feature Review and How to Upgrade from Connector/J 5.1
 
OpenStack Summit Portland April 2013 talk - Quantum and EC2
OpenStack Summit Portland April 2013 talk - Quantum and EC2OpenStack Summit Portland April 2013 talk - Quantum and EC2
OpenStack Summit Portland April 2013 talk - Quantum and EC2
 
OSGi Community Event 2010 - Enterprise OSGi in WebSphere and Apache Aries
OSGi Community Event 2010 - Enterprise OSGi in WebSphere and Apache AriesOSGi Community Event 2010 - Enterprise OSGi in WebSphere and Apache Aries
OSGi Community Event 2010 - Enterprise OSGi in WebSphere and Apache Aries
 
Open Admin - GWT
Open Admin - GWTOpen Admin - GWT
Open Admin - GWT
 
JavaOne Update zur Java Plattform
JavaOne Update zur Java PlattformJavaOne Update zur Java Plattform
JavaOne Update zur Java Plattform
 
Comet and the Rise of Highly Interactive Websites
Comet and the Rise of Highly Interactive WebsitesComet and the Rise of Highly Interactive Websites
Comet and the Rise of Highly Interactive Websites
 
Ed presents JSF 2.2 at a 2013 Gameduell Tech talk
Ed presents JSF 2.2 at a 2013 Gameduell Tech talkEd presents JSF 2.2 at a 2013 Gameduell Tech talk
Ed presents JSF 2.2 at a 2013 Gameduell Tech talk
 
GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0
 

Ähnlich wie HTML5 Websockets and Java - Arun Gupta

HTML5 WebSocket Introduction
HTML5 WebSocket IntroductionHTML5 WebSocket Introduction
HTML5 WebSocket IntroductionMarcelo Jabali
 
[English version] JavaFX and Web Integration
[English version] JavaFX and Web Integration[English version] JavaFX and Web Integration
[English version] JavaFX and Web IntegrationKazuchika Sekiya
 
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011Peter Moskovits
 
Consuming Java EE in Desktop, Web, and Mobile Frontends
Consuming Java EE in Desktop, Web, and Mobile FrontendsConsuming Java EE in Desktop, Web, and Mobile Frontends
Consuming Java EE in Desktop, Web, and Mobile FrontendsGeertjan Wielenga
 
Building Living Web Applications with HTML5 WebSockets
Building Living Web Applications with HTML5 WebSocketsBuilding Living Web Applications with HTML5 WebSockets
Building Living Web Applications with HTML5 WebSocketsPeter Moskovits
 
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/CamelCamelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/CamelCharles Moulliard
 
Programming WebSockets with Glassfish and Grizzly
Programming WebSockets with Glassfish and GrizzlyProgramming WebSockets with Glassfish and Grizzly
Programming WebSockets with Glassfish and GrizzlyC2B2 Consulting
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Masoud Kalali
 
How Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web DevelopmentHow Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web DevelopmentBruno Borges
 
Ebs troubleshooting con9019_pdf_9019_0001
Ebs troubleshooting con9019_pdf_9019_0001Ebs troubleshooting con9019_pdf_9019_0001
Ebs troubleshooting con9019_pdf_9019_0001jucaab
 
Have You Seen Java EE Lately?
Have You Seen Java EE Lately?Have You Seen Java EE Lately?
Have You Seen Java EE Lately?Reza Rahman
 
B1 roadmap to cloud platform with oracle web logic server-oracle coherence ...
B1   roadmap to cloud platform with oracle web logic server-oracle coherence ...B1   roadmap to cloud platform with oracle web logic server-oracle coherence ...
B1 roadmap to cloud platform with oracle web logic server-oracle coherence ...Dr. Wilfred Lin (Ph.D.)
 
HTML5 Real-Time and Connectivity
HTML5 Real-Time and ConnectivityHTML5 Real-Time and Connectivity
HTML5 Real-Time and ConnectivityPeter Lubbers
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureFrank Greco
 
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
Project Avatar (Lyon JUG & Alpes JUG  - March 2014)Project Avatar (Lyon JUG & Alpes JUG  - March 2014)
Project Avatar (Lyon JUG & Alpes JUG - March 2014)David Delabassee
 

Ähnlich wie HTML5 Websockets and Java - Arun Gupta (20)

HTML5 WebSocket Introduction
HTML5 WebSocket IntroductionHTML5 WebSocket Introduction
HTML5 WebSocket Introduction
 
[English version] JavaFX and Web Integration
[English version] JavaFX and Web Integration[English version] JavaFX and Web Integration
[English version] JavaFX and Web Integration
 
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011
Extending JMS to Web Devices over HTML5 WebSockets - JavaOne 2011
 
JavaCro'14 - Consuming Java EE Backends in Desktop, Web, and Mobile Frontends...
JavaCro'14 - Consuming Java EE Backends in Desktop, Web, and Mobile Frontends...JavaCro'14 - Consuming Java EE Backends in Desktop, Web, and Mobile Frontends...
JavaCro'14 - Consuming Java EE Backends in Desktop, Web, and Mobile Frontends...
 
Consuming Java EE in Desktop, Web, and Mobile Frontends
Consuming Java EE in Desktop, Web, and Mobile FrontendsConsuming Java EE in Desktop, Web, and Mobile Frontends
Consuming Java EE in Desktop, Web, and Mobile Frontends
 
Building Living Web Applications with HTML5 WebSockets
Building Living Web Applications with HTML5 WebSocketsBuilding Living Web Applications with HTML5 WebSockets
Building Living Web Applications with HTML5 WebSockets
 
Jspx Jdc2010
Jspx Jdc2010Jspx Jdc2010
Jspx Jdc2010
 
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/CamelCamelone-2012 HTML5 WebSocket ActiveMQ/Camel
Camelone-2012 HTML5 WebSocket ActiveMQ/Camel
 
Programming WebSockets with Glassfish and Grizzly
Programming WebSockets with Glassfish and GrizzlyProgramming WebSockets with Glassfish and Grizzly
Programming WebSockets with Glassfish and Grizzly
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
 
How Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web DevelopmentHow Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web Development
 
Ebs troubleshooting con9019_pdf_9019_0001
Ebs troubleshooting con9019_pdf_9019_0001Ebs troubleshooting con9019_pdf_9019_0001
Ebs troubleshooting con9019_pdf_9019_0001
 
Have You Seen Java EE Lately?
Have You Seen Java EE Lately?Have You Seen Java EE Lately?
Have You Seen Java EE Lately?
 
Con5133
Con5133Con5133
Con5133
 
B1 roadmap to cloud platform with oracle web logic server-oracle coherence ...
B1   roadmap to cloud platform with oracle web logic server-oracle coherence ...B1   roadmap to cloud platform with oracle web logic server-oracle coherence ...
B1 roadmap to cloud platform with oracle web logic server-oracle coherence ...
 
JavaCro'14 - WebLogic-GlassFish-JaaS Strategy and Roadmap – Duško Vukmanović
JavaCro'14 - WebLogic-GlassFish-JaaS Strategy and Roadmap – Duško VukmanovićJavaCro'14 - WebLogic-GlassFish-JaaS Strategy and Roadmap – Duško Vukmanović
JavaCro'14 - WebLogic-GlassFish-JaaS Strategy and Roadmap – Duško Vukmanović
 
HTML5 Real-Time and Connectivity
HTML5 Real-Time and ConnectivityHTML5 Real-Time and Connectivity
HTML5 Real-Time and Connectivity
 
Jetty Vs Tomcat
Jetty Vs TomcatJetty Vs Tomcat
Jetty Vs Tomcat
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the Future
 
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
Project Avatar (Lyon JUG & Alpes JUG  - March 2014)Project Avatar (Lyon JUG & Alpes JUG  - March 2014)
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
 

Mehr von JAX London

Everything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexityEverything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexityJAX London
 
Devops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick DeboisDevops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick DeboisJAX London
 
Busy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript AppsBusy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript AppsJAX London
 
It's code but not as we know: Infrastructure as Code - Patrick Debois
It's code but not as we know: Infrastructure as Code - Patrick DeboisIt's code but not as we know: Infrastructure as Code - Patrick Debois
It's code but not as we know: Infrastructure as Code - Patrick DeboisJAX London
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerJAX London
 
Worse is better, for better or for worse - Kevlin Henney
Worse is better, for better or for worse - Kevlin HenneyWorse is better, for better or for worse - Kevlin Henney
Worse is better, for better or for worse - Kevlin HenneyJAX London
 
Java performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha GeeJava performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha GeeJAX London
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias WessendorfHTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias WessendorfJAX London
 
Play framework 2 : Peter Hilton
Play framework 2 : Peter HiltonPlay framework 2 : Peter Hilton
Play framework 2 : Peter HiltonJAX London
 
Complexity theory and software development : Tim Berglund
Complexity theory and software development : Tim BerglundComplexity theory and software development : Tim Berglund
Complexity theory and software development : Tim BerglundJAX London
 
Why FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave GruberWhy FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave GruberJAX London
 
Akka in Action: Heiko Seeburger
Akka in Action: Heiko SeeburgerAkka in Action: Heiko Seeburger
Akka in Action: Heiko SeeburgerJAX London
 
NoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim BerglundNoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim BerglundJAX London
 
Closures, the next "Big Thing" in Java: Russel Winder
Closures, the next "Big Thing" in Java: Russel WinderClosures, the next "Big Thing" in Java: Russel Winder
Closures, the next "Big Thing" in Java: Russel WinderJAX London
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJAX London
 
Mongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdamsMongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdamsJAX London
 
New opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian RobinsonNew opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian RobinsonJAX London
 
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian PloskerThe Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian PloskerJAX London
 
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...JAX London
 

Mehr von JAX London (20)

Everything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexityEverything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexity
 
Devops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick DeboisDevops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick Debois
 
Busy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript AppsBusy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript Apps
 
It's code but not as we know: Infrastructure as Code - Patrick Debois
It's code but not as we know: Infrastructure as Code - Patrick DeboisIt's code but not as we know: Infrastructure as Code - Patrick Debois
It's code but not as we know: Infrastructure as Code - Patrick Debois
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
 
Worse is better, for better or for worse - Kevlin Henney
Worse is better, for better or for worse - Kevlin HenneyWorse is better, for better or for worse - Kevlin Henney
Worse is better, for better or for worse - Kevlin Henney
 
Java performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha GeeJava performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha Gee
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias WessendorfHTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
 
Play framework 2 : Peter Hilton
Play framework 2 : Peter HiltonPlay framework 2 : Peter Hilton
Play framework 2 : Peter Hilton
 
Complexity theory and software development : Tim Berglund
Complexity theory and software development : Tim BerglundComplexity theory and software development : Tim Berglund
Complexity theory and software development : Tim Berglund
 
Why FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave GruberWhy FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave Gruber
 
Akka in Action: Heiko Seeburger
Akka in Action: Heiko SeeburgerAkka in Action: Heiko Seeburger
Akka in Action: Heiko Seeburger
 
NoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim BerglundNoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim Berglund
 
Closures, the next "Big Thing" in Java: Russel Winder
Closures, the next "Big Thing" in Java: Russel WinderClosures, the next "Big Thing" in Java: Russel Winder
Closures, the next "Big Thing" in Java: Russel Winder
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk Pepperdine
 
Mongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdamsMongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdams
 
New opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian RobinsonNew opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian Robinson
 
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian PloskerThe Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
 
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
 

HTML5 Websockets and Java - Arun Gupta

  • 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 !  Flavors of 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 ? !  Establish a connection (Single TCP connection) !  Send messages in both direction (Bi-directional) !  Send message independent of each other (Full Duplex) !  End the connection 6 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 7. What does it add over TCP ? !  Origin-based security model for browsers !  Adds an addressing and protocol naming mechanism to support multiple services on one port !  Layers a framing mechanism on top of TCP !  Includes an additional in-band closing handshake 7 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 8. Establish a connection Handshake Request Client Server Handshake Response 8 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 9. 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 " 9 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 10. Handshake Response HTTP/1.1 101 Switching Protocols
 Upgrade: websocket
 Connection: Upgrade
 Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 Sec-WebSocket-Protocol: chat " 10 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 11. Establishing a Connection Handshake Request Client Server Handshake Response Connected ! 11 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 12. WebSocket Lifecycle Connected ! open open message message message message Client error Server message close Disconnected 12 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 13. WebSocket API www.w3.org/TR/websockets/ 13 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 14. 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 14 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 15. Browser Support 15 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. http://caniuse.com/websockets
  • 16. 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 16 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 17. 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 17 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 18. 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 18 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 19. Java API for WebSocket Features !  Create WebSocket Endpoints –  Annotation-driven (@WebSocketEndpoint) –  Interface-driven (Endpoint) !  SPI for extensions and data frames !  Integration with Java EE Web container 19 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 20. Touring the APIs 20 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 21. Note: The APIs might change before final release ! 21 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 22. Hello World and Basics POJO 22 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 23. Hello World import javax.net.websocket.annotations.*;
 
 @WebSocketEndpoint("/hello")
 public class HelloBean {
 
 @WebSocketMessage
 public String sayHello(String name) {
 return “Hello “ + name;
 }
 }" 23 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 24. 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 24 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 25. @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 25 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 26. Custom Payloads @WebSocketEndpoint(
 path="/hello",
 encoders={MyMessage.class},
 decoders={MyMessage.class}
 )
 public class MyEndpoint {
 . . .
 }" " " 26 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 27. 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();
 }
 }" 27 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 28. 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) {
 . . .
 }
 }" 28 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 29. Chat Sample @WebSocketEndpoint(path="/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);
 }
 
 . . ." 29 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 30. Chat Sample . . .
 
 @WebSocketMessage" public void message(String message, Session client) {" for (Session peer : peers) {
 peer.getRemote().sendObject(message);
 }
 }
 }" 30 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 31. URI Template Matching !  Level 1 only @WebSocketEndpoint(“/orders/{order-id}”)
 public class MyEndpoint {
 @WebSocketMessage
 public void processOrder(
 @WebSocketPathParam(“order-id”)String orderId) {
 . . .
 }
 } 31 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 32. Which methods can be @WebSocketMessage ? !  A parameter type that can be decoded in incoming message –  String, byte[] 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[] or any type for which there is a decoder 32 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 33. 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 33 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 34. WebSocket Subprotocols TBD 34 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 35. WebSocket Extensions !  Add capabilities to the base protocol –  Endpoints negotiate during opening handshake –  “Formal” or Private (prefixed with “x-”) !  Multiplexing –  http://tools.ietf.org/html/draft-tamplin-hybi-google-mux !  Compression: Only non-control frames/messages –  Per-frame: http://tools.ietf.org/html/draft-tyoshino-hybi-websocket-perframe-deflate –  Per-message: http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression 35 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 36. WebSocket Extensions Early Work . . . !  Extension.createIncomingFrameHandler, createOutgoingFrameHandler" !  Added to EndpointConfiguration" 36 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 37. Packaging – Java EE Style !  Client side !  Classes + resources packaged as a JAR !  Web Container !  Classes + resources packaged in a WAR file 37 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 38. Hello World and Basics Non-POJO 38 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 39. 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) {
 }
 } 
 });
 }
 }" 39 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 40. 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 *" 40 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 41. 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) {
 // . . . 
 }
 }
 }" 41 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 42. 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 42 –  Request URI Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 43. 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 43 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 44. Object Model Message Remote Handler Endpoint Client Session WebSocket Endpoint Message Remote Handler Endpoint Client Internet Session Message Handler Remote Client Endpoint Session 44 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 45. 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 45 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 46. 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)" 46 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 47. Relationship with Servlet 3.1 !  Allows a portable way to upgrade HTTP request !  New API –  HttpServletRequest.upgrade(ProtocolHandler handler)" 47 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 48. 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 48 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 49. Advanced Features !  DataFrame SPI !  Integration with Java EE and Web Applications –  Injectable components 49 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 50. 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 50 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 51. How to view WebSocket messages ? Capture traffic on loopback 51 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 52. How to view WebSocket messages ? chrome://net-internals -> Sockets -> View live sockets 52 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 53. WebSocket Future ??? !  Protocol Updates !  HTTP 2.0 !  SPDY 53 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 54. 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 54 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 55. Q&A 55 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 56. Graphic Section Divider 56 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 57. 57 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.