首页 > 其他分享 >CSharp的@microsoft/signalr实时通信教程 - 前端 vue

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

时间:2023-07-03 23:33:49浏览次数:45  
标签:vue console log signalR tt error signalr connection CSharp

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 出错');
}

 

标签:vue,console,log,signalR,tt,error,signalr,connection,CSharp
From: https://www.cnblogs.com/zhulongxu/p/17524462.html

相关文章

  • 编程开发 --- vue是什么
    只面向视图层的html模板引擎只面向视图层指的是可以在浏览器独立运行且只关注视图。模板引擎指的是使得html具备完备编程语言的特性。比如if语句 Vue是一种用于构建用户界面的渐进式JavaScript框架。它是一个开源项目,由尤雨溪(EvanYou)开发,并得到了广泛的社区支持和贡献。Vue......
  • Vue-生命周期
       <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title></head><body><divid="app"><divv-for="addrinaddrs&q......
  • Vue01
    1.简单了解前端的发展过程最初的网页以HTML为主,是纯静态的网页。网页是只读的,信息流只能从服务端到客户端单向流通。开发人员也只关心页面的样式和内容即可。1995年,网景工程师BrendanEich花了10天时间设计了JavaScript语言.2005年开始,ajax逐渐被前端开发人员所重视,因为不用......
  • Vue-指令-v-for
     <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title></head><body><divid="app"><divv-for="addrinaddrs"&g......
  • Vue-CoreVideoPlayer 视频播放器组件
    安装cnpminstall-Svue-core-video-player快速使用#在main.js中importVueCoreVideoPlayerfrom'vue-core-video-player'Vue.use(VueCoreVideoPlayer)#默认是英文的'''做国际化'''importVueCoreVideoPlayerfrom'vue-core-video......
  • Vue-指令-v-on
     <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title></head><body><divid="app"><inputtype="button"value="......
  • CSharp的Where底层实现
    usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net.Http;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;//命名空间namespacepro01{//类internalclassProgram{//main方法......
  • Vue-指令-v-if和v-show
     <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title></head><body><divid="app"><divv-if="count==3">di......
  • Vue-指令-v-bind和v-model
      <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title></head><body><divid="app"><av-bind:href="url">点击一下&......
  • Vue-快速入门
     <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title></head><body><divid="app"><inputv-model="username">......