websocket.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import { ElMessage } from 'element-plus'
  2. import useWSStore from '../store/modules/websocket'
  3. let websocket: WebSocket | null = null; // 用于存储实例化后websocket
  4. let rec: any; // 断线重连后,延迟5秒重新创建WebSocket连接 rec用来存储延迟请求的代码
  5. // @ts-ignore
  6. const baseUrl = import.meta.env.VITE_APP_WS_API;
  7. // 创建websocket
  8. function creatWebSocket(wsUrl: string) {
  9. console.log("websocket=================="+wsUrl);
  10. // 判断当前浏览器是否支持WebSocket
  11. if ("WebSocket" in window) {
  12. console.log("当前浏览器支持 WebSocket");
  13. } else if ("MozWebSocket" in window) {
  14. console.log("当前浏览器支持 MozWebSocket");
  15. } else {
  16. console.log("当前浏览器不支持 WebSocket");
  17. }
  18. try {
  19. initWebSocket(wsUrl); // 初始化websocket连接
  20. } catch (e) {
  21. console.log("尝试创建连接失败");
  22. reConnect(wsUrl); // 如果无法连接上 webSocket 那么重新连接!可能会因为服务器重新部署,或者短暂断网等导致无法创建连接
  23. }
  24. }
  25. // 初始化websocket
  26. function initWebSocket(wsUrl: string) {
  27. wsUrl = baseUrl+wsUrl;
  28. wsUrl = wsUrl.replace("http","ws");
  29. wsUrl = wsUrl.replace("https","wss");
  30. if(wsUrl.indexOf("s://") == -1){
  31. var start = window.location.href.split("://")[0];
  32. start = start.replace("http","ws");
  33. start = start.replace("https","wss");
  34. wsUrl =start+"://"+ window.location.href.split("://")[1].split("/")[0]+wsUrl
  35. }
  36. websocket = new WebSocket(wsUrl);
  37. // console.log("websocket:", websocket);
  38. websocket.onopen = function () {
  39. websocketOpen();
  40. };
  41. // // 接收
  42. websocket.onmessage = function (e: MessageEvent<any>) {
  43. websocketonmessage(e);
  44. };
  45. // 连接发生错误
  46. websocket.onerror = function () {
  47. console.log("WebSocket连接发生错误");
  48. // isConnect = false; // 连接断开修改标识
  49. reConnect(wsUrl); // 连接错误 需要重连
  50. };
  51. websocket.onclose = function (e) {
  52. websocketclose(e);
  53. };
  54. }
  55. // 定义重连函数
  56. let reConnect = (wsUrl: string) => {
  57. debugger
  58. console.log("尝试重新连接");
  59. if (useWSStore().isConnected()) return; // 如果已经连上就不在重连了
  60. rec && clearTimeout(rec);
  61. rec = setTimeout(function () {
  62. // 延迟5秒重连 避免过多次过频繁请求重连
  63. creatWebSocket(wsUrl);
  64. }, 5000);
  65. };
  66. // 创建连接
  67. function websocketOpen() {
  68. console.log("连接成功");
  69. useWSStore().connect(); // 修改连接状态
  70. }
  71. // 数据接收
  72. function websocketonmessage(e: MessageEvent<any>) {
  73. // console.log("数据接收", e.data);
  74. const data = JSON.parse(e.data); // 解析JSON格式的数据
  75. useWSStore().setMessage(data); // 存储数据
  76. // let data = JSON.parse(decodeUnicode(e.data))
  77. }
  78. // 关闭
  79. function websocketclose(e: any) {
  80. console.log(e);
  81. useWSStore().disconnect(); // 修改连接状态
  82. console.log("connection closed (" + e.code + ")");
  83. }
  84. // 数据发送
  85. function websocketsend(data: any) {
  86. console.log("发送的数据", data, JSON.stringify(data));
  87. if (websocket && useWSStore().isConnected()) { // 检查连接状态
  88. websocket.send(JSON.stringify(data));
  89. } else {
  90. ElMessage({
  91. showClose: true,
  92. message: "请选择设备连接",
  93. type: 'error',
  94. })
  95. }
  96. }
  97. // 实际调用的方法==============
  98. // 发送
  99. function sendWebSocket(data: any) {
  100. // 如果未保持连接状态 不允许直接发送消息 提示请选择连接设备
  101. if (!useWSStore().isConnected()) {
  102. ElMessage({
  103. showClose: true,
  104. message: "请选择设备连接",
  105. type: 'error',
  106. })
  107. } else {
  108. websocketsend(data);
  109. console.log("------------------");
  110. }
  111. }
  112. // 关闭
  113. let closeWebSocket = () => {
  114. if (websocket) {
  115. websocket.close();
  116. ElMessage({
  117. showClose: true,
  118. message: "设备已关闭",
  119. type: 'success',
  120. })
  121. }
  122. };
  123. let dostartWebSocket = () => {
  124. if (!websocket) {
  125. let data = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
  126. var r = Math.random() * 16 | 0, v = c == "x"? r : (r & 0x3 | 0x8);
  127. return v.toString(16);
  128. })
  129. initWebSocket("/ws/realtimedata/data");
  130. }
  131. };
  132. export {
  133. initWebSocket,
  134. sendWebSocket,
  135. creatWebSocket,
  136. closeWebSocket,
  137. dostartWebSocket,
  138. }