| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- import { ElMessage } from 'element-plus'
- import useWSStore from '../store/modules/websocket'
- let websocket: WebSocket | null = null; // 用于存储实例化后websocket
- let rec: any; // 断线重连后,延迟5秒重新创建WebSocket连接 rec用来存储延迟请求的代码
- // @ts-ignore
- const baseUrl = import.meta.env.VITE_APP_WS_API;
- // 创建websocket
- function creatWebSocket(wsUrl: string) {
- console.log("websocket=================="+wsUrl);
- // 判断当前浏览器是否支持WebSocket
- if ("WebSocket" in window) {
- console.log("当前浏览器支持 WebSocket");
- } else if ("MozWebSocket" in window) {
- console.log("当前浏览器支持 MozWebSocket");
- } else {
- console.log("当前浏览器不支持 WebSocket");
- }
- try {
- initWebSocket(wsUrl); // 初始化websocket连接
- } catch (e) {
- console.log("尝试创建连接失败");
- reConnect(wsUrl); // 如果无法连接上 webSocket 那么重新连接!可能会因为服务器重新部署,或者短暂断网等导致无法创建连接
- }
- }
- // 初始化websocket
- function initWebSocket(wsUrl: string) {
- wsUrl = baseUrl+wsUrl;
- wsUrl = wsUrl.replace("http","ws");
- wsUrl = wsUrl.replace("https","wss");
- if(wsUrl.indexOf("s://") == -1){
- var start = window.location.href.split("://")[0];
- start = start.replace("http","ws");
- start = start.replace("https","wss");
- wsUrl =start+"://"+ window.location.href.split("://")[1].split("/")[0]+wsUrl
- }
- websocket = new WebSocket(wsUrl);
- // console.log("websocket:", websocket);
- websocket.onopen = function () {
- websocketOpen();
- };
- // // 接收
- websocket.onmessage = function (e: MessageEvent<any>) {
- websocketonmessage(e);
- };
- // 连接发生错误
- websocket.onerror = function () {
- console.log("WebSocket连接发生错误");
- // isConnect = false; // 连接断开修改标识
- reConnect(wsUrl); // 连接错误 需要重连
- };
- websocket.onclose = function (e) {
- websocketclose(e);
- };
- }
- // 定义重连函数
- let reConnect = (wsUrl: string) => {
- console.log("尝试重新连接");
- if (useWSStore().isConnected()) return; // 如果已经连上就不在重连了
- rec && clearTimeout(rec);
- rec = setTimeout(function () {
- // 延迟5秒重连 避免过多次过频繁请求重连
- creatWebSocket(wsUrl);
- }, 5000);
- };
- // 创建连接
- function websocketOpen() {
- console.log("连接成功");
- useWSStore().connect(); // 修改连接状态
- }
- // 数据接收
- function websocketonmessage(e: MessageEvent<any>) {
- // console.log("数据接收", e.data);
- const data = JSON.parse(e.data); // 解析JSON格式的数据
- useWSStore().setMessage(data); // 存储数据
- // let data = JSON.parse(decodeUnicode(e.data))
- }
- // 关闭
- function websocketclose(e: any) {
- console.log(e);
- useWSStore().disconnect(); // 修改连接状态
- console.log("connection closed (" + e.code + ")");
- }
- // 数据发送
- function websocketsend(data: any) {
- console.log("发送的数据", data, JSON.stringify(data));
- if (websocket && useWSStore().isConnected()) { // 检查连接状态
- websocket.send(JSON.stringify(data));
- } else {
- ElMessage({
- showClose: true,
- message: "请选择设备连接",
- type: 'error',
- })
- }
- }
- // 实际调用的方法==============
- // 发送
- function sendWebSocket(data: any) {
- // 如果未保持连接状态 不允许直接发送消息 提示请选择连接设备
- if (!useWSStore().isConnected()) {
- ElMessage({
- showClose: true,
- message: "请选择设备连接",
- type: 'error',
- })
- } else {
- websocketsend(data);
- console.log("------------------");
- }
- }
- // 关闭
- let closeWebSocket = () => {
- if (websocket) {
- websocket.close();
- ElMessage({
- showClose: true,
- message: "设备已关闭",
- type: 'success',
- })
- }
- };
- let dostartWebSocket = () => {
- if (!websocket) {
- let data = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
- var r = Math.random() * 16 | 0, v = c == "x"? r : (r & 0x3 | 0x8);
- return v.toString(16);
- })
- initWebSocket("/ws/realtimedata/data");
- }
- };
- export {
- initWebSocket,
- sendWebSocket,
- creatWebSocket,
- closeWebSocket,
- dostartWebSocket,
- }
|