test.html 1.5 KB

12345678910111213141516171819202122232425262728293031323334
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <body>
  4. <h1>Websocket test client</h1>
  5. <input id="url" type="text" placeholder="Type URL" value="ws://localhost:8000/websocket" style="width:20em;" />
  6. <button id="connect">connect</button>
  7. <div style="height: 0.3em;">&nbsp;</div>
  8. <input id="message" type="text" placeholder="Type message" style="width: 20em;" />
  9. <button id="send">send message</button>
  10. <div style="margin-top: 1em;">Event log:</div>
  11. <div id="log" style="background: #eee; height: 10em; padding: 0.5em;"><div>
  12. </body>
  13. <script>
  14. var ws, E = function(id) { return document.getElementById(id); };
  15. var url = E('url'), connect = E('connect'), message = E('message'), send = E('send'), log = E('log');
  16. var enable = function(en) { message.disabled = send.disabled = !en; url.disabled = en; connect.innerHTML = en ? 'disconnect' : 'connect'; };
  17. enable(false)
  18. connect.onclick = function() {
  19. if (ws) { ws.close(); return; }
  20. ws = new WebSocket(url.value);
  21. if (!ws) return;
  22. ws.onopen = function() { log.innerHTML += 'CONNECTION OPENED<br/>'; }
  23. ws.onmessage = function(ev) { log.innerHTML += 'RECEIVED: ' + ev.data + '<br/>'; }
  24. ws.onerror = function(ev) { log.innerHTML += 'ERROR: ' + ev + '<br/>'; }
  25. ws.onclose = function() { log.innerHTML += 'CONNECTION CLOSED<br/>'; enable(false); ws = null; }
  26. enable(true);
  27. };
  28. send.onclick = function() {
  29. if (!ws) return;
  30. log.innerHTML += 'SENT: ' + message.value + '<br/>';
  31. ws.send(message.value);
  32. }
  33. </script>
  34. </html>