Wednesday, November 19, 2014

Java - Websockets (for the uninitiated) using Tomcat 7



What is a Websocket?

For the protocol agnostic, websocket is an improved web request that allows sending multiple requests over a period of time without having to reconnect with the server. It is more or less like a network socket in Java. Once a connection is established between two entities (initiated by the client), both entities can freely communicate with each other.


For a more detailed explanation on the subject, please visit http://en.wikipedia.org/wiki/WebSocket

Below is a pictographic representation of websockets 




How does this help an application?
  1. The server can push messages to the client rather than waiting for the client to pull data.
    • Once the client initiates connections, the server will be able to push notifications to the client at any time. This enables notifications from the server
  2. Reduced network I/O
    • Only the first request is a HTTP request. Once the connection is established, the messages are sent as a simple TCP message. This removes most of the HTTP overheads thus reducing the I/O between the entities.
  3. Reduced overheads of authenticating every request from the same client
    • When the connection is established, the connection can be authenticated one time. One authenticated, further messages can be trusted and there is no need for authenticating further messages. This hugely improves performance of chatty systems
Support on browsers

Web applications can now use websockets to communicate with servers. Most modern browsers support the protocol and can be implemented with simple javascript.

A secure version of the WebSocket protocol is implemented in Firefox 6, Safari 6, Google Chrome 14, Opera 12.10 and Internet Explorer 10

Websockets in Java (using tomcat 7's implementation)

With respect to the Java community, websocket implementations are based on JSR356. Being only a reference, there are many implementations each requiring support for several other features.

  1. Tomcat provides support for websockets with its own implementation since version 7.0.27
  2. JavaEE 7 provides a default implementation for Websockets that can be used on applications using and running on JavaEE7.
In this post, we will talk about using Tomcat's implementation. Since most of our apps do not need a full fledged application server, a simple Servlet container such as Tomcat is more than sufficient for most of our apps. So this blog would elaborate on this.

Server example

Steps
  1. Setup the application
    • Create a Java Web app.
    • Create a simple Servlet class that extends "WebSocketServlet" rather than the "HttpServlet"
    • Add the below entry to "web.xml" to route URL hits to the websocket server.
      • <servlet>
                <servlet-name>Server</servlet-name>
                <servlet-class>
                    com.corenttech.websocket.Server
                    <servlet-class>
            </servlet>
            <servlet-mapping>
                <servlet-name>Server</servlet-name>
                <url-pattern>/Server</url-pattern>
            </servlet-mapping>
      •  Since this is a servlet, Tomcat decides if a HTTP request is a WebSocket request based on the URL that you have mapped to your servlet in web.xml or using annotations.
  2. Implementing a message listener.
    • WebSocketServlet is an abstract class that would require the below method to be implemented.
      • protected StreamInbound createWebSocketInbound(String string, HttpServletRequest hsr)
      • return a message listener (sample given below) in this method
        • return new MessageListener();
      • So, the servlet code should look like this
      • public class Server extends WebSocketServlet {
            @Override
            protected StreamInbound createWebSocketInbound(String protocol, HttpServletRequest hsr) {
                return new MessageListener();
            }  
        }
    • Assuming that the messages are going to be simple text, create the message listener class.
    • import java.io.IOException;
      import java.nio.ByteBuffer;
      import java.nio.CharBuffer;
      import org.apache.catalina.websocket.MessageInbound;

      public class MessageListener extends MessageInbound {

          @Override
          protected void onBinaryMessage(ByteBuffer bb) throws IOException {
              throw new UnsupportedOperationException("Not supported yet.");
          }

          @Override
          protected void onTextMessage(CharBuffer message) throws IOException {
              String msg = message.toString();
              //modify the message by adding a timestamp
              handleMessage(msg);
          }

          private void handleMessage(String msg) {
              msg = "(" + System.currentTimeMillis()+") "+ msg;
              System.out.println("Received Message " + msg);
          }
         
      }
    • If you wish to be notified when a WebSocket connection is opened or closed, simply override the onOpen and onClose methods in the MessageListener class
      @Override
      protected void onOpen(WsOutbound outbound);
      @Override
      protected void onClose(int status);
  3. Testing the server implementation
    1. We will concentrate only on the server side of the implementation as there are numerous examples of the client side code using javascript and also the client.
    2. For testing our implementation, we can use the chrome app named Simple WebSocket Client
    3. The URL of the websocket server will be
      1. ws://localhost:8080/WebsocketServer/Server

No comments:

Post a Comment