Understanding WebSockets versus Ajax/REST for Java EE Developers

From Resin 4.0 Wiki

Revision as of 00:00, 14 March 2012 by Rick (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Cookbook-48.pngWeb-48.png

Construction-48.png



            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="";       

               }

Personal tools
TOOLBOX
LANGUAGES