Tuesday Oct 16, 2012

WebSocket Applications using Java: JSR 356 Early Draft Now Available (TOTD #183)

WebSocket provide a full-duplex and bi-directional communication protocol over a single TCP connection. JSR 356 is defining a standard API for creating WebSocket applications in the Java EE 7 Platform. This Tip Of The Day (TOTD) will provide an introduction to WebSocket and how the JSR is evolving to support the programming model.

First, a little primer on WebSocket!

WebSocket is a combination of IETF RFC 6455 Protocol and W3C JavaScript API (still a Candidate Recommendation). The protocol defines an opening handshake and data transfer. The API enables Web pages to use the WebSocket protocol for two-way communication with the remote host.

Unlike HTTP, there is no need to create a new TCP connection and send a chock-full of headers for every message exchange between client and server. The WebSocket protocol defines basic message framing, layered over TCP. Once the initial handshake happens using HTTP Upgrade, the client and server can send messages to each other, independent from the other. There are no pre-defined message exchange patterns of request/response or one-way between client and and server. These need to be explicitly defined over the basic protocol.

The communication between client and server is pretty symmetric but there are two differences:
  • A client initiates a connection to a server that is listening for a WebSocket request.
  • A client connects to one server using a URI. A server may listen to requests from multiple clients on the same URI.

Other than these two difference, the client and server behave symmetrically after the opening handshake. In that sense, they are considered as "peers".

After a successful handshake, clients and servers transfer data back and forth in conceptual units referred as "messages". On the wire, a message is composed of one or more frames. Application frames carry payload intended for the application and can be text or binary data. Control frames carry data intended for protocol-level signaling.

Now lets talk about the JSR!

The Java API for WebSocket is worked upon as JSR 356 in the Java Community Process. This will define a standard API for building WebSocket applications. This JSR will provide support for:
  • Creating WebSocket Java components to handle bi-directional WebSocket conversations
  • Initiating and intercepting WebSocket events
  • Creation and consumption of WebSocket text and binary messages
  • The ability to define WebSocket protocols and content models for an application
  • Configuration and management of WebSocket sessions, like timeouts, retries, cookies, connection pooling
  • Specification of how WebSocket application will work within the Java EE security model
Tyrus is the Reference Implementation for JSR 356 and is already integrated in GlassFish 4.0 Promoted Builds.

And finally some code!

The API allows to create WebSocket endpoints using annotations and interface. This TOTD will show a simple sample using annotations. A subsequent blog will show more advanced samples.

A POJO can be converted to a WebSocket endpoint by specifying @WebSocketEndpoint and @WebSocketMessage.
public class HelloBean {
    public String sayHello(String name) {         return "Hello " + name + "!";     }
  • @WebSocketEndpoint marks this class as a WebSocket endpoint listening at URI defined by the value attribute.
  • The @WebSocketMessage identifies the method that will receive the incoming WebSocket message. This first method parameter is injected with payload of the incoming message. In this case it is assumed that the payload is text-based. It can also be of the type byte[] in case the payload is binary. A custom object may be specified if decoders attribute is specified in the @WebSocketEndpoint. This attribute will provide a list of classes that define how a custom object can be decoded.

    This method can also take an optional Session parameter. This is injected by the runtime and capture a conversation between two endpoints.
  • The return type of the method can be String, byte[] or a custom object. The encoders attribute on @WebSocketEndpoint need to define how a custom object can be encoded.
The client side is an index.jsp with embedded JavaScript. The JSP body looks like:

<div style="text-align: center;">
<form action="">
    <input onclick="say_hello()" value="Say Hello" type="button">
        <input id="nameField" name="name" value="WebSocket" type="text"><br>
<div id="output"></div>
The code is relatively straight forward. It has an HTML form with a button that invokes say_hello() method and a text field named nameField. A div placeholder is available for displaying the output.

Now, lets take a look at some JavaScript code:

<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:8080/HelloWebSocket/hello";
    var websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };
    function init() {         output = document.getElementById("output");     }     function say_hello() {      websocket.send(nameField.value);         writeToScreen("SENT: " + nameField.value);     }

  • This application is deployed as "HelloWebSocket.war" (download here) on GlassFish 4.0 promoted build 57. So the WebSocket endpoint is listening at "ws://localhost:8080/HelloWebSocket/hello". A new WebSocket connection is initiated by specifying the URI to connect to.
  • The JavaScript API defines callback methods that are invoked when the connection is opened (onOpen), closed (onClose), error received (onError), or a message from the endpoint is received (onMessage).
  • The client API has several send methods that transmit data over the connection. This particular script sends text data in the say_hello method using nameField's value from the HTML shown earlier.
  • Each click on the button sends the textbox content to the endpoint over a WebSocket connection and receives a response based upon implementation in the sayHello method shown above.
How to test this out ?
  1. Download the entire source project here or just the WAR file.
  2. Download GlassFish4.0 build 57 or later and unzip.
  3. Start GlassFish as "asadmin start-domain".
  4. Deploy the WAR file as "asadmin deploy HelloWebSocket.war".
  5. Access the application at http://localhost:8080/HelloWebSocket/index.jsp.

After clicking on "Say Hello" button, the output would look like:

Here are some references for you:
Subsequent blogs will discuss the following topics (not necessary in that order) ...
  • Binary data as payload
  • Custom payloads using encoder/decoder
  • Error handling
  • Interface-driven WebSocket endpoint
  • Java client API
  • Client and Server configuration
  • Security
  • Subprotocols
  • Extensions
  • Other topics from the API
  • Capturing WebSocket on-the-wire messages

Wednesday Oct 03, 2012

JavaOne 2012 DEMOgrounds, Book Signing, Java Leaders Dinner, and Juggy

Some pictures from the conference ...

And some pictures from the Java Leaders Dinner ..

Some more pictures from the dinner with Juggy ...

And some more pictures ...

And finaly the evolving album ...

Monday Oct 01, 2012

JavaOne 2012 Keynote and GlassFish Party Pictures

Some pictures from the keynote ...

And some pictures from the GlassFish Party ...

And the evolving album ...


profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.

Java EE 7 Samples

Stay Connected


« October 2012 »