Monday, March 4, 2013

Websocket Demo

Here is a small sample to illustrate interacting with a websocket service using javascript.  I found the running echo service online at websocket.org.  The functionality of this service is that you send it a message and it sends the data back to you using the websocket events.   This sample code just spins off a few calls to the service (using milliseconds as differentiation) and writes the responses out to the document.  It is pretty straight forward, but does give you a working example.

The javascript:
   var wsUri = "wss://echo.websocket.org/";  
   var output;  
   function init() {  
     output = document.getElementById("output");  
     testWebSocket();  
   }  
   function testWebSocket() {  
     websocket = new WebSocket(wsUri);  
     websocket.onopen = function (evt) { onOpen(evt) };  
     websocket.onclose = function (evt) { onClose(evt) };  
     websocket.onmessage = function (evt) { onMessage(evt) };  
     websocket.onerror = function (evt) { onError(evt) };  
   }  
   function onOpen(evt) {  
     writeToScreen("CONNECTED");  
     var text = new Date();  
     doSend(text.getMonth() + 1 + '-' + text.getDate() + '-' + text.getFullYear() + ' at ' + text.getMilliseconds());  
   }  
   function onClose(evt) {  
     writeToScreen("DISCONNECTED");  
   }  
   function onMessage(evt) {  
     writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');  
     setTimeout(onOpen(), 1250);  
   }  
   function onError(evt) {  
     writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);  
   }  
   function doSend(message) {  
     writeToScreen("SENT: " + message);  
     websocket.send(message);  
   }  
   function writeToScreen(message) {  
     var pre = document.createElement("p");  
     pre.style.wordWrap = "break-word";  
     pre.innerHTML = message;  
     output.appendChild(pre);  
     if (output.children.length > 20) {  
       websocket.close();  
     }  
   }  
   window.addEventListener("load", init, false);  
The page:
 <h2>WebSocket Test</h2>  
 <div id="output"></div>