websockettest.html 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>My WebSocket</title>
  5. </head>
  6. <body>
  7. Welcome<br/>
  8. <input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
  9. <div id="message">
  10. </div>
  11. </body>
  12. <script type="text/javascript">
  13. function freshpage(){
  14. //获取总高度
  15. var heigh = document.body.scrollHeight;
  16. window.scrollTo(0,heigh);
  17. }
  18. var websocket = null;
  19. // var ipAdress = getUrlParms("ipAdress");
  20. var fileName = getUrlParms("fileName");
  21. var host = getUrlParms("ipAdress");
  22. //判断当前浏览器是否支持WebSocket
  23. if('WebSocket' in window){
  24. websocket = new WebSocket("ws://" + host + ":7771/webSocket/"+fileName);
  25. // websocket = new WebSocket("ws://localhost:7771/webSocket/"+"入参");
  26. }
  27. else{
  28. alert('Not support websocket')
  29. }
  30. //连接发生错误的回调方法
  31. websocket.onerror = function(){
  32. setMessageInnerHTML("error");
  33. };
  34. //连接成功建立的回调方法
  35. websocket.onopen = function(event){
  36. setMessageInnerHTML("open");
  37. }
  38. //接收到消息的回调方法
  39. websocket.onmessage = function(event){
  40. setMessageInnerHTML(event.data);
  41. freshpage();
  42. }
  43. //连接关闭的回调方法
  44. websocket.onclose = function(){
  45. setMessageInnerHTML("close");
  46. }
  47. //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  48. window.onbeforeunload = function(){
  49. websocket.close();
  50. }
  51. //将消息显示在网页上
  52. function setMessageInnerHTML(innerHTML){
  53. document.getElementById('message').innerHTML += innerHTML + '<br/>';
  54. }
  55. //关闭连接
  56. function closeWebSocket(){
  57. websocket.close();
  58. }
  59. //发送消息
  60. function send(){
  61. var message = document.getElementById('text').value;
  62. websocket.send(message);
  63. }
  64. //获取地址栏参数,name:参数名称
  65. function getUrlParms(name){
  66. var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
  67. var r = window.location.search.substr(1).match(reg);
  68. if(r!=null)
  69. return unescape(r[2]);
  70. return null;
  71. }
  72. </script>
  73. </html>