Files
Yi.Admin/Yi.Bbs.Vue3/src/utils/signalR.js

44 lines
1.2 KiB
JavaScript
Raw Normal View History

2024-01-04 21:37:35 +08:00
// 官方文档https://docs.microsoft.com/zh-cn/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.2&tabs=visual-studio
import * as signalR from "@microsoft/signalr";
import useAuths from "@/hooks/useAuths";
const { getToken } = useAuths();
export default {
SR: {},
start(url,callFunc) {
2024-01-04 21:37:35 +08:00
const connection = new signalR.HubConnectionBuilder()
.withUrl(`${import.meta.env.VITE_APP_BASE_WS}/` + url, {
headers: {
Authorization: `Bearer ${getToken()}`,
},
accessTokenFactory: () => {
// 返回授权 token
return `${getToken()}`;
},
})
.withAutomaticReconnect(new ForeverRetryPolicy()) //自动重新连接
.configureLogging(signalR.LogLevel.Error)
2024-01-04 21:37:35 +08:00
.build();
this.SR = connection;
// 断线重连
connection.onclose(() => {
console.log("hub断开");
2024-01-04 21:37:35 +08:00
});
connection.onreconnected(() => {
console.log("hub重新连接成功");
2024-01-04 21:37:35 +08:00
});
callFunc(connection);
2024-01-04 21:37:35 +08:00
// 启动
this.SR.start();
2024-01-04 21:37:35 +08:00
},
2024-01-04 21:37:35 +08:00
};
class ForeverRetryPolicy {
nextRetryDelayInMilliseconds(retryContext) {
return 1000*3;
}
}