signalR封装及使用

文章展示了如何在Vue应用中封装SignalR连接,包括初始化连接、配置跨域、处理身份验证、错误重连以及调用服务端方法。同时,提供了断开连接的方法,并给出了在组件挂载时如何使用封装好的signalR进行连接和事件监听。
摘要由CSDN通过智能技术生成

封装

import * as signalR from '@microsoft/signalr'
import { api } from '../../boot/axios'
// 如果需要身份验证 .withUrl("/messageHub", {accessTokenFactory: () => sessionStorage.getItem("token")})
export default {
  connection: {},
  // 开始signalr连接
  connect: async function () {
    const _this = this
    const res = await api({
      method: 'get',
      url: '/xxxx'
    })
    let 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'
    onMounted(async () => {
      // 连接signalr
      await signalr.connect()
      // xxx为监听的接口
      signalr.connection.on('xxx', (res) => {
        console.log('--------------', res)
      })
    })

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值