websock.htm 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4. <title>Test</title>
  5. <script type='text/javascript' language="javascript">
  6. <!--
  7. var connection;
  8. var keepAlive = false;
  9. function webSockKeepAlive() {
  10. if (keepAlive) {
  11. connection.send('ping'); // Send the message 'ping' to the server
  12. setTimeout("webSockKeepAlive()", 10000);
  13. }
  14. }
  15. function load() {
  16. connection = new WebSocket("ws://127.0.0.1/MyWebSock");
  17. connection.onopen = function () {
  18. var send = "init " + Math.round(Math.random()*4294967294+1);
  19. console.log('Client: ' + send);
  20. connection.send(send);
  21. keepAlive = true;
  22. webSockKeepAlive();
  23. };
  24. connection.onerror = function (error) {
  25. keepAlive = false;
  26. connection.close();
  27. console.log('WebSocket error: ' + error);
  28. alert("WebSocket error");
  29. };
  30. connection.onmessage = function (e) {
  31. console.log('Server: ' + e.data);
  32. if (e.data.substring(0,5) == "title") {window.document.title = e.data.substring(6);}
  33. else if (e.data.substring(0,3) == "msg") {
  34. var msgStr = document.getElementById('msg');
  35. msgStr.innerHTML = msgStr.innerHTML + e.data.substring(4);
  36. }
  37. };
  38. }
  39. //-->
  40. </script>
  41. </head>
  42. <body onload="load()">
  43. <input type="button" onclick="connection.send('msg A');" value="A"></button>
  44. <input type="button" onclick="connection.send('msg B');" value="B"></button>
  45. <input type="button" onclick="connection.send('msg C');" value="C"></button>
  46. <input type="button" onclick="connection.send('msg D');" value="D"></button>
  47. <b id="msg"></b>
  48. </body>
  49. </html>