WebSocket Rocks

By | 30 June, 2013


<!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");
 //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) {
 doSend("WebSocket rocks");
 //Listen for the close connection event then call the writeToScreen function
 function onClose(evt) {
 //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>');
 //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);
 //Display logging information in the HTML document
 function writeToScreen(message) {
 var pre = document.createElement("p");
 pre.style.wordWrap = "break-word";
 pre.innerHTML = message;

//Also log information on the javascript console

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

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

Leave a Reply

Your email address will not be published.