13 changed files with 173 additions and 102 deletions
@ -0,0 +1,57 @@ |
|||||||
|
import * as signalR from '@microsoft/signalr' |
||||||
|
export default { |
||||||
|
SR: {}, |
||||||
|
// 初始化连接
|
||||||
|
initSR: 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 as any).start().then(() => { |
||||||
|
console.log('加入聊天室',id) |
||||||
|
that.SR.send("joinRoom", id) |
||||||
|
}); |
||||||
|
} catch (err) { |
||||||
|
setTimeout(start, 5000); |
||||||
|
} |
||||||
|
} |
||||||
|
// 5.关闭之后重连
|
||||||
|
(that.SR as any).onclose(async () => { |
||||||
|
if ((that.SR as any).flag) { |
||||||
|
await start(); |
||||||
|
} |
||||||
|
}); |
||||||
|
|
||||||
|
// 6.启动连接
|
||||||
|
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(); |
||||||
|
} |
||||||
|
|
||||||
|
}; |
Loading…
Reference in new issue