Understanding WebSockets versus Ajax/REST for Java EE Developers

From Resin 4.0 Wiki

Revision as of 00:00, 15 March 2012 by Rick (Talk | contribs)
Jump to: navigation, search

Cookbook-48.pngWeb-48.png

Construction-48.png

Contents

Understanding WebSockets versus Ajax: Tutorial for Java Developers

There has been a lot of discussion lately about WebSockets. WebSocket client API is part of HTML 5. WebSocket wire protocol that handles the low-level handshaking, framing, and negotiation was just released in 2012. WebSocket has been a multi year work in progress that just completed.

You can use WebSocket from a browser like you can Ajax. But when should use WebSockets and when should you use Ajax? Also, can you use WebSocket from other clients? This tutorial is going to try to answer that question. Its aim is to be a compare, contrast and learn tutorial. In order to convey the information we add enough code to make it go beyond the pointy hair boss description. To do this, we slowly build a chat client and server.

Let's do a quick code comparison of the JavaScript and Java involved in doing Ajax and WebSockets to start off the discussion. To developers sometimes code examples are very demystifying.


Ajax simple example client (JavaScript/Browser/HTML 5) and server (Resin Java Application Server)

The following code listing is a simple JavaScript Ajax, HTML 5 example that sends a "Hello Ajax World?" message to our server.

Sample Ajax "Chat" with RAW JavaScript/HTML 5


	var ajax = null;
	
	function sendChatMessageAjax() {                   //(2)
	    if (ajax == null) {                                         
	    	ajax = new XMLHttpRequest();                 //(1)
	    }    
	    
		if (ajax.readyState == 4 || ajax.readyState == 0) {
			document.getElementById("span_result").innerHTML = "SENDING AJAX MESSAGE";

			ajax.open("POST", 'chat', true);
			ajax.onreadystatechange = handleChatMessageAjaxResponse;  //(3)
			ajax.send("Hello Ajax World?");
		}
	}
	function handleChatMessageAjaxResponse() {
		if (ajax.readyState == 4) {
			document.getElementById('span_result').innerHTML = ajax.responseText;
		}
	}
...
<body>
	<br />
	<a href="javascript:sendChatMessageAjax();">Send Chat Message via
		Ajax</a>
	<br />
	<a href="javascript:sendChatMessageWebSocket();">Send Chat Message
		via WebSocket</a>
	<br />
	<a href="javascript:clearSend();">Clear send results</a>
	<br />
	<span id="span_result"></span>
	<span id="error_result"></span>

</body>

Now typically, you don't use XMLHttpRequest directly, instead you use jQuery or Prototype or any number of other JavaScript frameworks. But to ease the explanation, and to aid in comparison to WebSocket, let's start with raw JavaScript (later tutorials will use raw JavaScript, jQuery and Prototype).

Quick Review of Ajax: sendChatMessageAjax (2) is JavaScript function that uses an instance of XMLHttpRequest called ajax (1) to send an HTTP POST request back to the server. Since this is JavaScript, and you don't want to block the user and JavaScript does not support threads, then you must register a callback called handleChatMessageAjaxResponse with the ajax.onreadystatechange (XMLHttpRequest) (3).

Servlet that handles Ajax call

Now let's cover the Java side of the house. Again, there are many Java frameworks that add layers between the Java backend and the HTML/JavaScript rendering to handle Ajax nicely. But for this discussion, let's start with the simplest thing that will work, and in Java that is a Java HttpServlet as follows:

Sample Ajax "Chat" server with a RAW Java Servlet (Resin Java Application Server / Java EE)

package com.caucho.websocket.example;
...

/**
 * Servlet implementation class ChatServlet
 */
@WebServlet("/chat")
public class ChatServlet extends HttpServlet {
 
...       
    /**
     * Handle ajax calls
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("___________ doPost MEHTOD ________________ " );
        

        char [] data = new char[4096];
        request.getReader().read(data); // 1
        String text = new String(data); // 2
        
        System.out.println(text); //print out what the client sent
        
        response.getWriter().print("Hello from Server-side Ajax : " +text); //3
    }

}

This is fairly basic. Read the data (1), convert data into a String (2), send the data back to the browser with "Hello from Server-side Ajax : " prepended to to it (3).


WebSocket simple example client and server

Now lets compare the above client and server to a WebSocket equivalent. Efforts are made to keep this JavaScript really simple and easy to understand so it is easy to compare against the previous Ajax example.

The following code listing is a simple JavaScript Ajax, HTML 5 example that sends a "Hello WebSocket World?" message to our server.

I made the WebSocket example orthogonal as possible to Ajax example.

Sample WebSocket "Chat" server with a RAW Java Servlet (Resin Java Application Server / Java EE)


    var socket = null;
	
    function sendChatMessageWebSocket() {         // (2)
    	if (socket == null) {
    	     // (1)
    	    socket = new WebSocket("ws://localhost:8080/web-socket-example/chat", "caucho-example-chat-protocol");
    	    socket.onmessage = handleChatMessageWebSocketResponse;   //(3)
    	    initSocket(); //Explained later
    	}
	    document.getElementById("span_result").innerHTML = "SENDING WEBSOCKET MESSAGE";
	    socket.send("Hello WebSocket World?");
	}
	    
	function handleChatMessageWebSocketResponse(msg) {
	    document.getElementById("span_result").innerHTML = msg.data;
	}
        ...


Quick Run down of the WebSocket code: sendChatMessageWebSocket (2) is JavaScript function that uses an instance of WebSocket called socket (1) to start a WebSocket connection (HTTP upgrade) with the server. Since this is JavaScript, and you don't want to block the user and JavaScript does not support threads, then you must register a callback called handleChatMessageWebSocketResponse with the socket.onmessage (WebSocket) (3).

Ok so they look very similar. Again, I am going to start with the similarities. The differences are to come.

To handle the above you need a WebSocketListener handler as follows:



public class ChatWebSocketListener implements WebSocketListener {
    @Override
    public void onReadText(WebSocketContext context, Reader reader)
            throws IOException {
        System.out.println("___________ onReadText MEHTOD ________________ " );

        char [] data = new char[4096];
        
        reader.read(data);  // (1)
        
        String text = new String(data); // (2)
        System.out.println(text);
        
        PrintWriter out = context.startTextMessage();                      // (??? NEW 4)
        out.print("Hello from Server-side WebSocket : " + text); // (3)
        out.close(); //You have to close to send the message.             // (??? NEW 5)
        System.out.println("___________ onReadText MEHTOD END END END________________ " );

    }
   ...

This is fairly basic. Read the data (1), convert data into a String (2), send the data back to the browser with "Hello from Server-side Ajax : " prepended to to it (3).


At this point, these are nearly identical. You can use WebSockets similar to how you should use Ajax. No real learning curve for simple cases.

Some noticeable differences between WebSockets, and Ajax examples

The first difference between this and the Servlet version is that we are using a WebSocketListener. The WebSocketListener is a Resin class as Java EE 6 does not have WebSocket support. Java EE 6 predates Websocket. The WebSocketListener looks fairly similar to the Servlet API as much as possible by design.

Note that the current plan for Java EE 7 is to include WebSocket support. Caucho Technology is and has been involved in several Java EE JSRs, and was heavily involved in the IETF WebSocket draft.

From a programming perspective, so far, there is no real difference between the WebSocket version and the Ajax/Servlet version. There is a little bit of handshaking that the Servlet has to do which we will cover later, but essentially if this is all you wanted, then WebSocket looks a lot like Ajax. Now since we are developing a chat example, eventually we will want to push messages from other people who are in the chat session. This is where WebSockets is going to shine.

What is WebSockets again?

From a web developers viewpoint, WebSocket is a new browser feature for HTML 5 browsers. This new feature enables richer user interactions. Both the browser and the server can send asynchronous messages over a single TCP socket, without doing less scalable hacks like long polling or comet.

The communication starts out like HTTP and then upgrades after a HTTP handshake to bidirectional websockets. A WebSocket is a bidirectional message stream between the client and the server.

While all modern browsers support WebSocket as of March 2012 few application servers and web servers do. In order for browsers to take advantage of WebSockets, you need to have an application server or web server that can handle WebSockets.

Detour Streaming API versus a byte[]/String API versus a WebSocket Frame API

There are several Java WebSocket implementations out in the wild. Resin WebSocket support is the most mature and gets used by more high traffic sites.

If you are not familiar with Resin Server, it is a super scalable, fast, mature Java EE certified application/web server. Its speed is faster than NginX and Apache HTTPD, and it is more scalable.

Resin's WebSocket support is not a side project or science project. All of Resin's cloud/clustering communication works on top of WebSocket and runs some of the highest traffic Java deployments in the world. Our WebSocket support predates most implementations. And Resin's websocket support has the most real world burn in for ultra high traffic sites. If you are serious about WebSockets and Java, then Resin Server is an obvious contender. Also you can try out the Open Source version for free.

Many Java WebSocket implementations do not allow stream access to WebSocket (Reader, Writer, InputStream, OutputStream), and instead rely on simple buffer constructs like String and byte[] or dump you down into working directly with low level WebSocket frames (Frame API). Since WebSocket is a streaming, framing wire protocol, naturally Resin Server supports streams. It is easy to for Java developers to go from streams to byte[] and String as shown in the above examples.

Regarding a Frame oriented API, when you program with TCP/IP you never have an application developer API that exposes TCP/IP packets bit mask fields, in the same way the WebSocket Frame is the wrong level of abstraction for most developers. Caucho Technology, with over 12 years of experience developing APIs, has come up with an API that is the right level of abstraction, i.e., streams. That said, we are always looking for feedback.

Now that we have the background in the why of the API, let's discuss how the streaming works.

WebSocket is unlike Ajax/HTTP in that the WebSocket connection stays open and it is bidirectional. This is perfect for a chat application or a near real time stock price app, etc.

WebSockets have two types of messages, binary (byte[]), and text (String). If your message is bigger than a single Frame then it gets sent as chunks in multiple frames.

To begin a message you need to send a stream of WebSocket frames. To start the message you call context.startTextMessage() (NEW 4). If your message does not fit into one frame, then a another frame is created and marked that it continues the previous frame in the series. In WebSockets the final frame is marked with a "finished" flag. This is sent final frame is sent when you call close on the stream. This final frame says that you are done sending the current binary or text message. The out.close (5) is your way to tell Resin's WebSocket implementation that the message is done so go ahead and mark the current frame as finished and then send that as the last frame. On the client end of the wire, websockets client implementation will see that the it got the last frame.

Get all of that? That is ok. Just remember to call close, and then Resin will complete sending the message just like you would write output to a Servlet or write to a file. WebSocket frames are a nice fit with the Java IO Stream and Reader/Writer APIs.

Now most of this framing and streaming is wasted on JavaScript/HTML 5 clients as they are simplified for client app development. The JavaScript API for WebSocket only deals with buffers like String and byte[] (these are String and ArrayBuffer or Blob in JavaScript speak). So why bother with a streaming API? Well to be honest you don't really need to worry about it with HTML5 clients, but WebSocket is a generally purpose framing/wire protocol so expect a lot of other uses. Many other protocols spend a lot of time and effort creating a framing protocol (AMQP, IIOP, RMI-JRMP, etc.). If you are developing a new protocol that needs framing, you can just build your new protocol on top of WebSocket.


(Full code listings will be at end of tutorial (this page.)

IN PROGRESS...

Personal tools
TOOLBOX
LANGUAGES