ws_test.html 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>WS Test</title>
  5. </head>
  6. <body>
  7. <h1>WebSocket Test</h1>
  8. <div id="status">Disconnected</div>
  9. <div id="log"></div>
  10. <script>
  11. const log = (msg) => {
  12. const div = document.createElement('div');
  13. div.textContent = msg;
  14. document.getElementById('log').appendChild(div);
  15. console.log(msg);
  16. };
  17. const wsUrl = 'ws://localhost:8000/api/v1/forums/1/ws';
  18. log('Connecting to ' + wsUrl);
  19. try {
  20. const ws = new WebSocket(wsUrl);
  21. ws.onopen = () => {
  22. document.getElementById('status').textContent = 'Connected';
  23. log('Connected!');
  24. ws.send('ping');
  25. };
  26. ws.onmessage = (e) => {
  27. log('Received: ' + e.data);
  28. };
  29. ws.onclose = (e) => {
  30. document.getElementById('status').textContent = 'Disconnected';
  31. log('Closed: ' + e.code + ' ' + e.reason);
  32. };
  33. ws.onerror = (e) => {
  34. log('Error: ' + JSON.stringify(e));
  35. };
  36. } catch (e) {
  37. log('Exception: ' + e);
  38. }
  39. </script>
  40. </body>
  41. </html>