封装:
import { api } from '../../boot/axios'
// 如果需要身份验证 .withUrl("/messageHub", {accessTokenFactory: () => sessionStorage.getItem("token")})
export default {
connection: {},
// 开始signalr连接
connect: async function () {
const _this = this
// 此处请求是因为signalr地址为动态的,需要从接口获取,如果固定地址直接赋值即可
const res = await api({
method: 'get',
url: '/xxxx'
})
const baseURL = res.Description
_this.connection = new signalR.HubConnectionBuilder()
.withUrl(baseURL, { crossDomain: true }) // 跨域需要使用绝对地址
.configureLogging(signalR.LogLevel.Information)
.build()
async function start () {
try {
await _this.connection.start()
console.log('signaR连接成功')
} catch (err) {
console.log('err', err)
setTimeout(start, 5000)
}
}
_this.connection.onclose(async (error) => {
console.log('error', error)
// 断线重连 error是空的话则是手动断开,不需要重连
if (error) await _this.connect()
})
start()
},
// 调用服务端方法
send: async function (methodName, param) {
try {
const _this = this
await _this.connection.invoke(methodName, param)
} catch (err) {
console.error(err)
}
},
// 断开连接
disconnect: async function () {
const _this = this
await _this.connection.stop()
}
}
使用: 引入封装好的signalR
import signalr from '../../assets/js/useSignalr'
连接signalR,监听接口
// 连接signalr
await signalr.connect()
// xxx为监听的接口
signalr.connection.on('xxx', (res) => {
console.log('--------------', res)
})
})```