xignalR新增加自动重连

This commit is contained in:
不做码农 2022-03-10 15:07:36 +08:00
commit a605e704e9

View File

@ -13,7 +13,8 @@ export default {
init(url) { init(url) {
const connection = new signalR.HubConnectionBuilder() const connection = new signalR.HubConnectionBuilder()
.withUrl(url, { accessTokenFactory: () => getToken() }) .withUrl(url, { accessTokenFactory: () => getToken() })
.withAutomaticReconnect()//自动重新连接 .withAutomaticReconnect()//自动重新连接
.configureLogging(signalR.LogLevel.Information)
.build(); .build();
this.SR = connection; this.SR = connection;
// 断线重连 // 断线重连
@ -31,16 +32,19 @@ export default {
// 启动 // 启动
// this.start(); // this.start();
}, },
/**
* 调用 this.signalR.start().then(async () => { await this.SR.invoke("method")})
* @returns
*/
async start() { async start() {
var that = this; var that = this;
try { try {
//使用async和await 或 promise的then 和catch 处理来自服务端的异常 //使用async和await 或 promise的then 和catch 处理来自服务端的异常
await this.SR.start(); await this.SR.start();
//console.assert(this.SR.state === signalR.HubConnectionState.Connected); //console.assert(this.SR.state === signalR.HubConnectionState.Connected);
console.log('signalR 连接成功了', this.SR.state); console.log('signalR 连接成功了', this.SR.state);
return true;
} catch (error) { } catch (error) {
that.failNum--; that.failNum--;
console.log(`失败重试剩余次数${that.failNum}`, error) console.log(`失败重试剩余次数${that.failNum}`, error)
@ -49,6 +53,7 @@ export default {
await this.SR.start() await this.SR.start()
}, 5000); }, 5000);
} }
return false;
} }
}, },
// 接收消息处理 // 接收消息处理