websocketDemo.html 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>666666</title>
  6. </head>
  7. <body>
  8. 传递来的数据值cid:
  9. <input type="text" th:value="${cid}" id="cid"/>
  10. <p>【toUserId】:
  11. <div><input id="toUserId" name="toUserId" type="text" value="user-1"></div>
  12. <p>【contentText】:
  13. <div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
  14. <p>【操作】:
  15. <div>
  16. <button type="button" onclick="sendMessage()">发送消息</button>
  17. </div>
  18. </body>
  19. <script type="text/javascript">
  20. var socket;
  21. if (typeof (WebSocket) == "undefined") {
  22. console.log("您的浏览器不支持WebSocket");
  23. } else {
  24. console.log("您的浏览器支持WebSocket");
  25. //实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
  26. var cid = document.getElementById("cid").value;
  27. console.log("cid-->" + cid);
  28. var reqUrl = "http://localhost:8080/websocket/" + cid;
  29. socket = new WebSocket(reqUrl.replace("http", "ws"));
  30. //打开事件
  31. socket.onopen = function () {
  32. alert("Socket 已打开");
  33. console.log("Socket 已打开");
  34. //socket.send("这是来自客户端的消息" + location.href + new Date());
  35. };
  36. //获得消息事件
  37. socket.onmessage = function (msg) {
  38. console.log("onmessage--" + msg.data);
  39. //发现消息进入 开始处理前端触发逻辑
  40. };
  41. //关闭事件
  42. socket.onclose = function () {
  43. console.log("Socket已关闭");
  44. };
  45. //发生了错误事件
  46. socket.onerror = function () {
  47. alert("Socket发生了错误");
  48. //此时可以尝试刷新页面
  49. }
  50. //离开页面时,关闭socket
  51. //jquery1.8中已经被废弃,3.0中已经移除
  52. // $(window).unload(function(){
  53. // socket.close();
  54. //});
  55. }
  56. function sendMessage() {
  57. if (typeof (WebSocket) == "undefined") {
  58. console.log("您的浏览器不支持WebSocket");
  59. } else {
  60. // console.log("您的浏览器支持WebSocket");
  61. var toUserId = document.getElementById('toUserId').value;
  62. var contentText = document.getElementById('contentText').value;
  63. var msg = '{"sid":"' + toUserId + '","message":"' + contentText + '"}';
  64. console.log(msg);
  65. socket.send(msg);
  66. }
  67. }
  68. </script>
  69. </html>