流浪のwolf

卷帝

导航

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

1. 安装@microsoft/signalr

pnpm install @microsoft/signalr --save


signalr  是微软对 websocket技术的封装,优化了操作 ;
1. build 和后端signalR服务建立关联
2. 使用 on 方法监听后端定义的函数,ps:此函数由后端触发,后端发送数据给前端
3. 使用 invoke 主动触发后端的函数,ps:由前端触发,前端可以发送数据给后端

2. 封装组件 js


import * as signalR from '@microsoft/signalr'
import { ref } from "vue"
const opt = ref<any>(
 {
  // 禁止协商
  skipNegotiation: true,
  // 使用 websocket 协议
  transport: signalR.HttpTransportType.WebSockets,
  // 启用日志
  logging: true
 }
)
opt.HttpMessageHandlerFactory = (handler: any) => {
 var newHandler = handler as any;
 newHandler.ServerCertificateCustomValidationCallback = (request: any, cert: any, chain: any, errors: any) => {
  return true;
 };
 return newHandler;
}

export function SignalR() {
 const _signalR: any = {
  connection: null,
  connectionStatus: false,
  // url 必须写全路径
  build(url: string) {
   console.log(url)
   const connection = new signalR.HubConnectionBuilder()
    .withUrl(url, opt.value)
    .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);
   console.log(signalR.HubConnectionState.Connected);

   // if (connection.state === signalR.HubConnectionState.Connected) {
   //   this.handles();
   // }
   this.handles()
   console.log('signalR初始化成功', this)
   return this
  },
  handles() {
   const that: any = this
   // Starts the connection.
   function start() {
    console.log('start方法执行');
    that.connection.start().then((message: any) => {
     console.log('start成功', message);
     that.startSuccess(message)
    }).catch((err: any) => {
     if (that.connectionStatus === true) {
      console.error("start失败", err)
      setTimeout(() => {
       start()
      }, 1000)
     }
    })
   }
   start()
   // invoked when the connection is closed.
   this.connection.onclose(async (error: any) => {
    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: any) => {
    this.reconnecting(error)
   })
   // invoked when the connection successfully reconnects.
   this.connection.onreconnected((connectionId: any) => {
    this.reconnectedSuccess(connectionId)
   })
  },
  stop() {
   // Stops the connection.
   this.connection && this.connection.stop().then(() => {
    this.stopSuccess()
   }).catch((err: any) => console.error(err))
  },
  startSuccess(message: any) {
   console.log(`start成功, ${message}`)
  },
  closeSuccess(message: any) {
   console.log(`close成功, ${message}`)
  },
  reconnecting(err: any) {
   console.log(`正在重连, ${err}`)
  },
  reconnectedSuccess(connectionId: any) {
   console.log(`reconnected成功, ${connectionId}`)
  },
  stopSuccess() {
   console.log(`stop stopSuccess成功`)
  },
  invoke(methodName: any, args: any) {
   console.log('invoke方法触发,传送args参数给后端,由客户端主动触发就用invoke');
   this.connection && this.connection.invoke(methodName, args).catch((err: any) => console.error("errerrerr", err))
  },
  on(methodName: any, newMethod = () => { }) {
   console.log('on方法触发 开始监听,由后端触发使用on监听,从后端接收数据')
   this.connection && this.connection.on(methodName, newMethod)
  },
  off(methodName: any, newMethod: any) {
   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.63:5965/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 出错'); }

 

posted on 2023-07-03 23:25  流浪のwolf  阅读(366)  评论(0编辑  收藏  举报