Understanding WebSockets versus Ajax/REST for Java EE Developers

From Resin 4.0 Wiki

(Difference between revisions)
Jump to: navigation, search
Line 13: Line 13:
 
For example:
 
For example:
  
===Sample Ajax "Chat" with RAW JavaScript===
+
===Sample Ajax "Chat" with RAW JavaScript/HTML 5===
 
<code> <pre>
 
<code> <pre>
  
var ajax = new XMLHttpRequest(); //1
+
var ajax = null;
 
+
function sendChatMessageAjax() { //2
+
function sendChatMessageAjax() {                   //(2)
 
+
    if (ajax == null) {                                       
 +
    ajax = new XMLHttpRequest();                //(1)
 +
    }   
 +
   
 
if (ajax.readyState == 4 || ajax.readyState == 0) {
 
if (ajax.readyState == 4 || ajax.readyState == 0) {
document.getElementById("span_result").innerHTML = "SENDING AJAX MESSAGE";  
+
document.getElementById("span_result").innerHTML = "SENDING AJAX MESSAGE";
  
 
ajax.open("POST", 'chat', true);
 
ajax.open("POST", 'chat', true);
ajax.onreadystatechange = handleChatMessageAjaxResponse; //3
+
ajax.onreadystatechange = handleChatMessageAjaxResponse; //(3)
 
ajax.send("Hello Ajax World?");
 
ajax.send("Hello Ajax World?");
 
}
 
}
 
}
 
}
function handleChatMessageAjaxResponse() { //4
+
function handleChatMessageAjaxResponse() {
 
if (ajax.readyState == 4) {
 
if (ajax.readyState == 4) {
 
document.getElementById('span_result').innerHTML = ajax.responseText;
 
document.getElementById('span_result').innerHTML = ajax.responseText;
Line 58: Line 61:
 
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:
 
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==
+
===Sample Ajax "Chat" server with a RAW Java Servlet (Resin Java Application Server / Java EE)===
 
<code> <pre>
 
<code> <pre>
 
package com.caucho.websocket.example;
 
package com.caucho.websocket.example;
Line 95: Line 98:
 
==WebSocket simple example client and server==
 
==WebSocket simple example client and server==
  
Now lets compare the above client and server to a WebSocket equivalent.
+
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.
  
 
<code> <pre>
 
<code> <pre>
  
var socket = new WebSocket("ws://localhost:8080/web-socket-example/chat",
+
    var socket = null;
"caucho-example-chat-protocol");
+
 
+
    function sendChatMessageWebSocket() {
socket.onmessage = function(msg) {
+
    if (socket == null) {
document.getElementById("span_result").innerHTML = msg.data;
+
        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?");
 
}
 
}
 
+
   
socket.onerror = function(msg) {
+
function handleChatMessageWebSocketResponse(msg) {
document.getElementById("error_result").innerHTML = "ERROR:" + msg;
+
    document.getElementById("span_result").innerHTML = msg.data;
 
}
 
}
 +
        ...
  
socket.onopen = function() {
+
</pre></code>
document.getElementById("span_result").innerHTML = "Socket Status: "
+
+ socket.readyState + " (open)";
+
}
+
socket.onclose = function() {
+
document.getElementById("span_result").innerHTML = "Socket Status: "
+
+ socket.readyState + " (Closed)";
+
  
}
 
  
function sendChatMessageWebSocket() {
+
Quick Run down of the WebSocket code: <code>sendChatMessageWebSocket</code> (2) is JavaScript function that uses an instance of <code>WebSocket</code> called <code>socket</code> (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 <code>handleChatMessageWebSocketResponse</code> with the <code>socket.onmessage (WebSocket)</code> (3).
  
document.getElementById("span_result").innerHTML = "SENDING WEBSOCKET MESSAGE";
+
Ok so they look very similar. Again, I am going to start with the similarities. The differences are to come.
socket.send("Hello WebSocket World?");
+
}
+
  
function clearSend() {
+
To handle the above you need a <code>WebSocketListener</code> handler as follows:
document.getElementById("span_result").innerHTML = "";
+
  
}
+
 
 +
<code> <pre>
 +
 
 +
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________________ " );
 +
 
 +
    }
 +
  ...
 
</pre></code>
 
</pre></code>
 +
 +
(Full code listings will be at end of tutorial (this page.)
 +
 +
IN PROGRESS...

Revision as of 00:00, 15 March 2012

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