websocket.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. console.log("尝试重新连接");
  58. if (useWSStore().isConnected()) return; // 如果已经连上就不在重连了
  59. rec && clearTimeout(rec);
  60. rec = setTimeout(function () {
  61. // 延迟5秒重连 避免过多次过频繁请求重连
  62. creatWebSocket(wsUrl);
  63. }, 5000);
  64. };
  65. // 创建连接
  66. function websocketOpen() {
  67. console.log("连接成功");
  68. useWSStore().connect(); // 修改连接状态
  69. }
  70. // 数据接收
  71. function websocketonmessage(e: MessageEvent<any>) {
  72. // console.log("数据接收", e.data);
  73. const data = JSON.parse(e.data); // 解析JSON格式的数据
  74. useWSStore().setMessage(data); // 存储数据
  75. // let data = JSON.parse(decodeUnicode(e.data))
  76. }
  77. // 关闭
  78. function websocketclose(e: any) {
  79. console.log(e);
  80. useWSStore().disconnect(); // 修改连接状态
  81. console.log("connection closed (" + e.code + ")");
  82. }
  83. // 数据发送
  84. function websocketsend(data: any) {
  85. console.log("发送的数据", data, JSON.stringify(data));
  86. if (websocket && useWSStore().isConnected()) { // 检查连接状态
  87. websocket.send(JSON.stringify(data));
  88. } else {
  89. ElMessage({
  90. showClose: true,
  91. message: "请选择设备连接",
  92. type: 'error',
  93. })
  94. }
  95. }
  96. // 实际调用的方法==============
  97. // 发送
  98. function sendWebSocket(data: any) {
  99. // 如果未保持连接状态 不允许直接发送消息 提示请选择连接设备
  100. if (!useWSStore().isConnected()) {
  101. ElMessage({
  102. showClose: true,
  103. message: "请选择设备连接",
  104. type: 'error',
  105. })
  106. } else {
  107. websocketsend(data);
  108. console.log("------------------");
  109. }
  110. }
  111. // 关闭
  112. let closeWebSocket = () => {
  113. if (websocket) {
  114. websocket.close();
  115. ElMessage({
  116. showClose: true,
  117. message: "设备已关闭",
  118. type: 'success',
  119. })
  120. }
  121. };
  122. let dostartWebSocket = () => {
  123. if (!websocket) {
  124. let data = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
  125. var r = Math.random() * 16 | 0, v = c == "x"? r : (r & 0x3 | 0x8);
  126. return v.toString(16);
  127. })
  128. initWebSocket("/ws/realtimedata/data");
  129. }
  130. };
  131. export {
  132. initWebSocket,
  133. sendWebSocket,
  134. creatWebSocket,
  135. closeWebSocket,
  136. dostartWebSocket,
  137. }