test_ws.html 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Test Websocket</title>
  8. </head>
  9. <body>
  10. <input type="text" id="message">
  11. <button id="submit">提交</button>
  12. <script>
  13. // 创建 websocket 实例
  14. let websocket = new WebSocket("ws://192.168.51.100:8888");
  15. // 处理连接打开的回调函数
  16. websocket.onopen = function() {
  17. console.log("连接建立");
  18. }
  19. // 处理收到消息的回调函数
  20. // 控制台打印消息
  21. websocket.onmessage = function(e) {
  22. console.log("收到消息: " + e.data);
  23. }
  24. // 处理连接异常的回调函数
  25. websocket.onerror = function() {
  26. console.log("连接异常");
  27. }
  28. // 处理连接关闭的回调函数
  29. websocket.onclose = function() {
  30. console.log("连接关闭");
  31. }
  32. // 实现点击按钮后, 通过 websocket 发送请求
  33. let input = document.querySelector('#message');
  34. let button = document.querySelector('#submit');
  35. button.onclick = function() {
  36. console.log("发送消息: " + input.value);
  37. websocket.send(input.value);
  38. }
  39. </script>
  40. </body>
  41. </html>