WebSocket Rocks

By | 30 June, 2013

Testing…

</pre>
<!DOCTYPE html>
 <meta charset="utf-8" />
 <meta name="author" content="Eugenia Pérez, eugenia_perez@cuatrovientos.org">
 <title>PSP I - Ex1 - WebSocket Test</title>

 <script language="javascript" type="text/javascript">

 //Global vars for websocket connection
 var wsUri = "wss://echo.websocket.org/";
 var output;
 //Initialize WebSocket connection and event handlers
 function init() {
 output = document.getElementById("output");
 testWebSocket();
 }
 //Inner method which manages the websocket lifecycle
 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) };
 }
 //Listen for the connection open event then call the writeToScreen function
 function onOpen(evt) {
 writeToScreen("CONNECTED");
 doSend("WebSocket rocks");
 }
 //Listen for the close connection event then call the writeToScreen function
 function onClose(evt) {
 writeToScreen("DISCONNECTED");
 }
 //Listen for new messages arriving at the cliente then call the writeToScreen function
 function onMessage(evt) {
 writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
 websocket.close();
 }
 //Listen for connection error then call the writeToScreen function with a given style format text
 function onError(evt) {
 writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
 }
 //Send a message on the WebSocket
 function doSend(message) {
 writeToScreen("SENT: " + message);
 websocket.send(message);
 }
 //Display logging information in the HTML document
 function writeToScreen(message) {
 var pre = document.createElement("p");
 pre.style.wordWrap = "break-word";
 pre.innerHTML = message;
 output.appendChild(pre);

//Also log information on the javascript console
 console.log(message);
 }

//Start running the example through the given listener
 window.addEventListener("load", init, false);
 </script>

<h2>WebSocket Test</h2>
 <div id="output"></div>
 </html>
<pre>
Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Leave a Reply

Your email address will not be published.