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

CSharp的@microsoft/signalr实时通信教程 - 前端 vue的更多相关文章

  1. [置顶] MVC中使用signalR入门教程

    一.前言:每次写总要说一点最近的感想 进入工作快半年了,昨天是最郁闷的一天,我怀疑我是不是得了"星期一综合征",每个星期一很没有状态.全身都有点酸痛,这个可能一个星期只有周末才打一 ...

  2. github上最全的资源教程-前端涉及的所有知识体系【转】

    github上最全的资源教程-前端涉及的所有知识体系[转自:蓝猫的博客] 综合类 综合类 地址 前端知识体系 http://www.cnblogs.com/sb19871023/p/3894452.h ...

  3. 史上最全面的SignalR系列教程-2、SignalR 实现推送功能-永久连接类实现方式

    1.概述 通过上篇史上最全面的SignalR系列教程-1.认识SignalR文章的介绍,我们对SignalR技术已经有了一个全面的了解.本篇开始就通过SignalR的典型应用的实现方式做介绍,例子虽然 ...

  4. 史上最全面的SignalR系列教程-6、SignalR 实现聊天室

    1.概述 通过前面几篇文章对SignalR的详细介绍.我们知道Asp.net SignalR是微软为实现实时通信的一个类库.一般情况下,SignalR会使用JavaScript的长轮询(long po ...

  5. SignalR系列教程:SignalR快速入门

    ---恢复内容开始--- 本篇是SignalR系列教程的第一篇,本篇内容介绍了如何创建SignalR应用,如何利用SignalR搭建简易的聊天室等,本篇内容参考自:http://www.asp.net ...

  6. 前后端不分离部署教程(基于Vue,Nginx)

    有小伙伴私信问我vue项目是如何进行前后端不分离打包发布的,那我岂能坐视不管,如此宠粉的我肯定是要给发一篇教程的,话不多说,开始操作 前端假如我们要发布我们的Vue项目,假设我们前端用的是histor ...

  7. 史上最全面的SignalR系列教程-3、SignalR 实现推送功能-集线器类实现方式

    1.概述 通过前两篇 史上最全面的SignalR系列教程-1.认识SignalR 史上最全面的SignalR系列教程-2.SignalR 实现推送功能-永久连接类实现方式 文章对SignalR的介绍, ...

  8. 史上最全面的SignalR系列教程-4、SignalR 自托管全解(使用Self-Host)-附各终端详细实例

    1.概述 通过前面几篇文章 史上最全面的SignalR系列教程-1.认识SignalR 史上最全面的SignalR系列教程-2.SignalR 实现推送功能-永久连接类实现方式 史上最全面的Signa ...

  9. 史上最全面的SignalR系列教程-5、SignalR 实现一对一聊天

    1.概述 通过前面几篇文章 史上最全面的SignalR系列教程-1.认识SignalR 史上最全面的SignalR系列教程-2.SignalR 实现推送功能-永久连接类实现方式 史上最全面的Signa ...

  10. 史上最全面的SignalR系列教程-目录汇总

    1.引言 最遗憾的不是把理想丢在路上,而是理想从未上路. 每一个将想法变成现实的人,都值得称赞和学习. 致正在奔跑的您! 2.SignalR介绍 SignalR实现服务器与客户端的实时通信 ,她是一个 ...

随机推荐

  1. 【Tutorial C】08 函数 Function

    函数的定义 C源程序是由函数组成的. 最简单的程序有一个主函数 main(),但实用程序往往由多个函数组成, 由主函数调用其他函数,其他函数也可以互相调用. 函数是C源程序的基本模块,程序的许多功能是 ...

  2. nvidia公司官方迁移学习套件 —— NVIDIA TAO Toolkit

    资料: https://blogs.nvidia.com/blog/what-is-transfer-learning/ 相关: https://developer.nvidia.com/tao-to ...

  3. anaconda环境下:强化学习PPO算法仿真环境库sample-factory的python完美适配版本为python3.11

    anaconda环境下:强化学习PPO算法仿真环境库sample-factory的python完美适配版本为python3.11 库sample-factory地址: https://github.c ...

  4. Jax框架的Traced object特性与TensorFlow的placeholder的一致性

    前文: Jax框架的static与Traced Operations -- Static vs Traced Operations 前文讨论分析了Jax的static特性和Traced特性,这些谈下个 ...

  5. 深度解读KubeEdge架构设计与边缘AI实践探索

    摘要:解读业界首个云原生边缘计算框架KubeEdge的架构设计,如何实现边云协同AI,将AI能力无缝下沉至边缘,让AI赋能边侧各行各业,构建智能.高效.自治的边缘计算新时代,共同探索智能边缘的新篇章. ...

  6. Java和LWJGL的关于OpenAL的文章

    一.OpenAL的原理和基本概念: 1.1 OpenAL的架构 OpenAL的架构同样基于三个核心组件:Context(上下文).Source(声源)和Buffer(缓冲区).Context代表了音频 ...

  7. awk批量提取序列

    在提取前需保证序列文件仅有一列! awk '{print$1}' input.fa > ouput.fa#就可将ID后面的其余注释信息去掉,仅保留ID 1 awk -F '>' 'NR=F ...

  8. CH01_初识C++

    CH01_初识C++ 第一个C++程序 新建项目 新建文件 编写代码 #include <iostream> using namespace std; int main() { cout ...

  9. 一种很变态但有效的DDD建模沟通方式

    本文书接上回<这就是为什么你学不会DDD>,关注公众号(老肖想当外语大佬)获取信息: 最新文章更新: DDD框架源码(.NET.Java双平台): 加群畅聊,建模分析.技术实现交流: 视频 ...

  10. java_GUI2

    package GUi;import java.awt.*;public class GuI2 { public static void main(String[] args) { MyFrame n ...