Understanding WebSockets versus Ajax/REST for Java EE Developers
From Resin 4.0 Wiki
var ajax = new XMLHttpRequest();
function sendChatMessageAjax() {
if (ajax.readyState == 4 || ajax.readyState == 0) {
document.getElementById("span_result").innerHTML="SENDING AJAX MESSAGE";
ajax.open("POST", 'chat', true);
ajax.onreadystatechange = handleChatMessageAjaxResponse;
ajax.send("Hello Ajax World?");
}
}
function handleChatMessageAjaxResponse() {
if (ajax.readyState == 4) {
document.getElementById('span_result').innerHTML = ajax.responseText;
}
}
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="";
}