view.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <!doctype html>
  2. <html>
  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">
  7. <link rel="shortcut icon" href="/favicon.ico"/>
  8. <title>webman</title>
  9. </head>
  10. <body>
  11. <?=htmlspecialchars($hello)?>
  12. </body>
  13. <script>
  14. function connect() {
  15. // 与服务端建立WebSocket连接
  16. //(为了方便测试这里ip使用的是127.0.0.1,正式环境请使用外网ip)
  17. ws = new WebSocket('ws://127.0.0.1:8888');
  18. // 连接建立后发送daping,表明自己是电脑浏览器
  19. ws.onopen = function() {
  20. ws.send('daping');
  21. };
  22. // 收到服务端推送的数据后,将数据显示在浏览器里(心跳数据pong除外)
  23. ws.onmessage = function (e) {
  24. if (e.data !== 'pong') {
  25. console.log(e.data)
  26. }
  27. };
  28. // 没隔50秒发送一个心跳数据 ping 给服务器,保持连接
  29. ws.timer = setInterval(function () {
  30. ws.send('ping');
  31. }, 5000);
  32. // 当连接关闭时清除定时器,并设置1秒后重连
  33. ws.onclose = function () {
  34. clearTimeout(ws.timer);
  35. setTimeout(connect, 1000);
  36. };
  37. }
  38. // 执行连接
  39. connect();
  40. </script>
  41. </html>