1、创建实例
const http = new Tool().http
const token=localStorage.getItem('token')?localStorage.getItem('token'):''
const connection = new signalR.HubConnectionBuilder()
.withUrl(http+"/event", {
accessTokenFactory:()=>{
let t ="Bearer "+token
return t ;
},
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets,
})
.build();
2、创建服务端长连接推送消息
//监听服务端长连接的推送消息
const emits = defineEmits(["tongXin"])
3、监听事件消息
//监听有新的待办事项
connection.on("OrderFlowChanged",(message) =>{
console.log('有新的待办事项推送的消息',message)
ElNotification({
title: '提示消息',
message: '您有新的待办事项,请前往订单中心-订单列表中处理!',
duration: 10000,
})
emits('tongXin', message)
})
4、通信开始
async function start() {
try {
await connection.start();
console.log("SignalR Connected.通信开始");
} catch (err) {
console.log(err,'通信报错');
if(isLogin.value){
console.log('重新链接')
setTimeout(start, 5000);
}else{
connection.stop();//窗口关闭断开通信
}
}
};
// 断线重连
connection.onclose(async () => {
console.log('断开连接了????????????')
if(isLogin.value){
console.log('重新链接')
await start();
}else{
connection.stop();//窗口关闭断开通信
}
});
onMounted(() => {
start();
})
//窗口销毁后
onUnmounted(() => {
isLogin.value=false
connection.stop();//窗口关闭断开通信
})