HTML Websockets

19 July 2017 Author: Erik Lievaart In this article I present a simple websocket testing page. Next I will explain the javascript involved.

A cross browser websocket tester



...

Code Example

The example above is a cross browser, jquery based websocket testing tool. Ideal for a tool, but for my explanation, I want to focus on a HTML / Javascript only example to keep things simple. Creating a web socket is as easy as: tester.html [10:10]
  ws = new WebSocket(url);
Next we assign handlers for the events we want to listen to: tester.html [13:23]
  ws.onopen = function() {
    document.getElementById('output').innerHTML = 'connected!<br>';
  };

  ws.onmessage = function(e){
    document.getElementById('output').innerHTML += 'in :' + e.data + '<br>';
  };

  ws.onclose = function() {
    document.getElementById('output').innerHTML = 'closed!<br>';
  };
Pushing a message to the server: tester.html [32:32]
    ws.send(data);
In my example I add two forms. One for opening the socket: tester.html [37:40]
<form>
    <input id="url" type="input" value="ws://example.com/" style="min-width: 100%;"/><br/>
    <input type="submit" onclick="openSocket(document.getElementById('url').value); return false;" value="open"/>
</form>
And one for sending a message: tester.html [42:45]
<form>
    <textarea id="json" rows="20" cols="100">boo!</textarea><br/>
    <input type="submit" onclick="send(document.getElementById('json').value); return false;" value="send"/>
</form>
As you might have seen in the code, this example appends all messages sent and received to a div with id "output". tester.html [47:47]
<code><div id="output">...</div></code>
Here is the complete code example that works on firefox: tester.html
<html>
<body>

<script>
function openSocket(url) {
  if (typeof ws !== 'undefined') {
    ws.close();
  }

  ws = new WebSocket(url);
  ws.binaryType = 'arraybuffer';

  ws.onopen = function() {
    document.getElementById('output').innerHTML = 'connected!<br>';
  };

  ws.onmessage = function(e){
    document.getElementById('output').innerHTML += 'in :' + e.data + '<br>';
  };

  ws.onclose = function() {
    document.getElementById('output').innerHTML = 'closed!<br>';
  };
  return false;
}

function send(data) {
  if (typeof ws === 'undefined') {
    document.getElementById('output').innerHTML = 'not connected!<br>';
  } else {
    document.getElementById('output').innerHTML += 'out:' + data + '<br>';
    ws.send(data);
  }
}
</script>

<form>
    <input id="url" type="input" value="ws://example.com/" style="min-width: 100%;"/><br/>
    <input type="submit" onclick="openSocket(document.getElementById('url').value); return false;" value="open"/>
</form>

<form>
    <textarea id="json" rows="20" cols="100">boo!</textarea><br/>
    <input type="submit" onclick="send(document.getElementById('json').value); return false;" value="send"/>
</form>

<code><div id="output">...</div></code>

</body>
</html>