CSharp的@microsoft/signalr实时通信教程 - 前端 vue

发布时间 2023-07-03 23:28:51作者: 流浪のwolf

1. 安装@microsoft/signalr

pnpm install @microsoft/signalr --save

2. 封装组件 js

import * as signalR from '@microsoft/signalr'

export function SignalR () {
 const _signalR = {
  connection: null,
  connectionStatus: false,
  build (url) {
   console.log(url)
   const connection = new signalR.HubConnectionBuilder()
    .withUrl(url, {
     skipNegotiation: true,
     transport: signalR.HttpTransportType.WebSockets
    })
    .withAutomaticReconnect({
     nextRetryDelayInMilliseconds: retryContext => {
      if (retryContext.elapsedMilliseconds < 60000) {
       // If we've been reconnecting for less than 60 seconds so far,
       // wait between 0 and 10 seconds before the next reconnect attempt.
       return 2000
      } else {
       // If we've been reconnecting for more than 60 seconds so far, stop reconnecting.
       return 5000
      }
     }
    })
    // .withAutomaticReconnect([0, 2000, 5 * 1000, 10 * 1000, 30 * 1000, 60 * 1000, 120 * 1000, 120 * 1000, 120 * 1000])
    .build()
   this.connection = connection
   // console.log(connection.state);
   // if (connection.state === signalR.HubConnectionState.Connected) {
   //   this.handles();
   // }
   console.log('ceshi')
   this.handles()
   console.log('signalR初始化成功')
   return this
  },
  handles () {
   const that = this
   // Starts the connection.
   function start () {
    that.connection.start().then(message => {
     that.startSuccess(message)
    }).catch((err) => {
     if (that.connectionStatus === true) {
      console.error(err)
      setTimeout(() => {
       start()
      }, 1000)
     }
    })
   }
   start()

   // invoked when the connection is closed.
   // this.connection.onclose(async error => {
   //   this.closeSuccess(`signalR connection closed. error: ${error}`);
   //   await this.connection.start();
   // });
   this.connection.onclose(error => {
    this.closeSuccess(`signalR connection closed. error: ${error}`)
   })
   // 重连时触发
   this.connection.onreconnecting(error => {
    this.reconnecting(error)
   })
   // invoked when the connection successfully reconnects.
   this.connection.onreconnected((connectionId) => {
    this.reconnectedSuccess(connectionId)
   })
  },
  stop () {
   // Stops the connection.
   this.connection && this.connection.stop().then(() => {
    this.stopSuccess()
   }).catch(err => console.error(err))
  },
  startSuccess (message) {
   console.log(`start成功, ${message}`)
  },
  closeSuccess (message) {
   console.log(`close成功, ${message}`)
  },
  reconnecting (err) {
   console.log(`正在重连, ${err}`)
  },
  reconnectedSuccess (connectionId) {
   // 连接成功
   console.log(`reconnected成功, ${connectionId}`)
  },
  stopSuccess () {
   console.log(`stop成功`)
  },
  invoke (methodName, args) {
   this.connection && this.connection.invoke(methodName, args).catch(err => console.error(err))
  },
  on (methodName, newMethod = () => { }) {
   console.log('on方法触发')
   this.connection && this.connection.on(methodName, newMethod)
  },
  off (methodName, newMethod) {
   if (!this.connection) {
    return false
   }
   if (newMethod) {
    this.connection.off(methodName, newMethod)
   } else {
    this.connection.off(methodName)
   }
  }
 }

 return _signalR
}

3. 使用   【 按需 】

import { SignalR } from '@/utils/signalR'
let si  = SignalR();
try {
 si.build('http://192.168.1.61:59765/chatHub')
 si.on("ReceiveMessage",(tt)=>{
  if(tt.substring(0,1) === "{") {
    tt = JSON.parse(tt)
    console.log('原来数据',tt,typeof tt);
    formInline.formData.barcodename = tt.BarcodeName
    formInline.formData.batch = tt.Batch
    formInline.formData.valid_s = tt.BirthDate
    formInline.formData.serial = tt.Serial
  }else {
   console.log('原来数据',tt,typeof tt);
   formInline.formData.tagid = tt
  }
})
} catch (error) {
 console.log('signarl 出错');
}