Understanding WebSockets versus Ajax/REST for Java EE Developers
From Resin 4.0 Wiki
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
var ajax = new XMLHttpRequest(); //1
function sendChatMessageAjax() { //2
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() { //4
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
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.
var socket = new WebSocket("ws://localhost:8080/web-socket-example/chat",
"caucho-example-chat-protocol");
socket.onmessage = function(msg) {
document.getElementById("span_result").innerHTML = msg.data;
}
socket.onerror = function(msg) {
document.getElementById("error_result").innerHTML = "ERROR:" + msg;
}
socket.onopen = function() {
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() {
document.getElementById("span_result").innerHTML = "SENDING WEBSOCKET MESSAGE";
socket.send("Hello WebSocket World?");
}
function clearSend() {
document.getElementById("span_result").innerHTML = "";
}