import * as signalR from '@microsoft/signalr' import { connect } from 'http2'; export default { SR: {}, // 初始化连接 initSR: async function (id) { const that = this // // 连接 SignalR const options: signalR.IHttpConnectionOptions = { accessTokenFactory: async () => { return sessionStorage.getItem('token') } } // 1.获取系统中定义的baseURL const url = '/hubs/taskchat' // 2.初始化连接 that.SR = new signalR.HubConnectionBuilder() .withUrl(url, options) .configureLogging(signalR.LogLevel.Information) .build(); // 3. 在停止signalR时,不让onclose内的 start执行 (that.SR as any).flag = true // 4.启动连接的方法 async function start() { try { await that.SR.start(); console.assert(that.SR.state === signalR.HubConnectionState.Connected) await that.SR.send("joinRoom", id).then(() => console.log("已加入聊天室")); } catch (err) { setTimeout(start, 5000); } } // 5.关闭之后重连 (that.SR as any).onclose(async () => { if ((that.SR as any).flag) { await start(); } }); // 6.启动连接 await start(); }, // 停止连接,因为调用that.SR.stop(),同时会触发5操作,所以用了flag stopSR: function () { let that = this; (that.SR as any).flag = false async function stop() { try { await that.SR.stop(); console.log("signaR退出成功"); } catch (err) { } } stop(); } };