ws_im.html 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Java后端WebSocket的Tomcat实现</title>
  5.    <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport' />
  6.    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7. </head>
  8. <body>
  9. Welcome<br/><input id="text" type="text"/>
  10. <button onclick="send()">发送消息</button>
  11. <hr/>
  12. <button onclick="closeWebSocket()">关闭WebSocket连接</button>
  13. <hr/>
  14. <div id="message"></div>
  15. </body>
  16. <script type="text/javascript">
  17. var websocket = null;
  18. //判断当前浏览器是否支持WebSocket
  19. if ('WebSocket' in window) {
  20. // websocket = new WebSocket("ws://127.0.0.1:8490?user_id=1&token=6fe83bc7831c3c5b");
  21. websocket = new WebSocket("ws://test-ws.mee.chat?user_id=1&token=6fe83bc7831c3c5b");
  22. }
  23. else {
  24. alert('当前浏览器 Not support websocket')
  25. }
  26. //连接发生错误的回调方法
  27. websocket.onerror = function (ex) {
  28. setMessageInnerHTML("WebSocket连接发生错误, ex:" + ex.message);
  29. };
  30. //连接成功建立的回调方法
  31. websocket.onopen = function () {
  32. setMessageInnerHTML("WebSocket连接成功");
  33. }
  34. //接收到消息的回调方法
  35. websocket.onmessage = function (event) {
  36. setMessageInnerHTML(event.data);
  37. }
  38. //连接关闭的回调方法
  39. websocket.onclose = function () {
  40. setMessageInnerHTML("WebSocket连接关闭");
  41. }
  42. //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  43. window.onbeforeunload = function () {
  44. closeWebSocket();
  45. }
  46. //将消息显示在网页上
  47. function setMessageInnerHTML(innerHTML) {
  48. document.getElementById('message').innerHTML += innerHTML + '<br/>';
  49. }
  50. //关闭WebSocket连接
  51. function closeWebSocket() {
  52. websocket.close();
  53. }
  54. //发送消息
  55. function send() {
  56. var message = document.getElementById('text').value;
  57. websocket.send(message);
  58. }
  59. </script>
  60. </html>