// import sysConfig from '@/config/index'
|
// import tool from '@/utils/tool'
|
import store from "../store/index";
|
import http from "@/../src/api/http.js";
|
import * as signalR from "@microsoft/signalr";
|
import { ElNotification } from "element-plus";
|
|
import eventBus from "./eventBus";
|
|
// import * as signalrMessage from './mqtt/message'
|
//使用signalr
|
export default function useSignalr() {
|
// const userInfo = tool.data.get('USER_INFO') //用户信息
|
let openedNotification = null; // 保存当前打开的Notification实例
|
let socketUrl = "hubs/simple"; //socket地址
|
// if (sysConfig.VITE_PROXY === 'false') {
|
socketUrl = http.ipAddress + socketUrl; //判断是否要走代理模式,走了的话发布之后直接nginx代理
|
// }
|
//开始
|
const startSignalr = () => {
|
//初始化连接
|
const connection = init();
|
// 启动连接
|
connection
|
.start()
|
.then(() => {
|
console.log("启动连接");
|
})
|
.catch((err) => {
|
console.log("连接失败", err);
|
});
|
};
|
|
//初始化
|
const init = () => {
|
console.log("初始化SignalR对象");
|
// SignalR对象
|
const connection = new signalR.HubConnectionBuilder()
|
.withUrl(socketUrl, {
|
accessTokenFactory: () => store.getters.getToken(),
|
skipNegotiation: true,
|
transport: signalR.HttpTransportType.WebSockets,
|
})
|
.withAutomaticReconnect({
|
nextRetryDelayInMilliseconds: () => {
|
return 5000; // 每5秒重连一次
|
},
|
}) //自动重新连接
|
.configureLogging(signalR.LogLevel.Information)
|
.build();
|
connection.keepAliveIntervalInMilliseconds = 15 * 1000; // 心跳检测15s
|
// connection.serverTimeoutInMilliseconds = 30 * 60 * 1000 // 超时时间30m
|
// 断开连接
|
connection.onclose(async () => {
|
console.log("断开连接");
|
});
|
|
//断线重新
|
connection.onreconnected(() => {
|
console.log("断线重新连接成功");
|
});
|
//消息处理
|
receiveMsg(connection);
|
return connection;
|
};
|
|
//接收消息处理
|
const receiveMsg = (connection) => {
|
//接收登出
|
connection.on("LoginOut", (data) => {
|
// signalrMessage.loginOut(data)
|
});
|
|
connection.on("NewMessage", (data) => {
|
eventBus.emit("stackerDataError", data);
|
if (openedNotification === null || openedNotification.closed) {
|
// 上一个Notification已关闭或尚未打开
|
openedNotification = ElNotification({
|
title: "成功",
|
message: data,
|
type: "success",
|
onClose: () => {
|
// Notification已关闭
|
openedNotification = null; // 清空当前打开的Notification实例
|
console.log("Notification已关闭");
|
},
|
});
|
}
|
});
|
|
connection.on("StackerData", (data) => {
|
// console.log(data);
|
eventBus.emit("stackerData", data);
|
});
|
connection.on("LineData", (data) => {
|
eventBus.emit("locationData", data);
|
});
|
connection.on("Logs", (data) => {
|
eventBus.emit("Logs", data);
|
});
|
};
|
|
//页面销毁
|
// onUnmounted(() => {})
|
return { startSignalr };
|
}
|