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. WebSockets are part of HTML 5. You can use them from a browser like you can Ajax. But when should use WebSockets and when should you use Ajax? This tutorial is going to try to answer that question. Its aim is to be a compare, contrast and learn tutorial.

Let's do a quick code comparison of the JavaScript and Java involved in doing Ajax and WebSockets.

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

For example:

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).

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 WebSocket : " +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 WebSocket : " 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. I made the WebSocket example orthogonal as possible to Ajax example.


    var socket = null;
	
    function sendChatMessageWebSocket() {
    	if (socket == null) {
    	    socket = new WebSocket("ws://localhost:8080/web-socket-example/chat", "caucho-example-chat-protocol");
    	    socket.onmessage = handleChatMessageWebSocketResponse;
    	    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 send 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);
        
        String text = new String(data);
        System.out.println(text);
        
        PrintWriter out = context.startTextMessage();
        out.print("Hello from Server-side WebSocket : " + text);
        out.flush();
        out.close(); //You have to close to send the message.
        System.out.println("___________ onReadText MEHTOD END END END________________ " );

    }
   ...

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

IN PROGRESS...

Personal tools
TOOLBOX
LANGUAGES