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. 【微信小程序】 分包

    1. 什么是分包 分包指的是把一-个完整的小程序项目,按照需求划分为不同的子包, 在构建时打包成不同的分包,用户在使用时按需进行加载. 2. 分包的好处 对小程序进行分包的好处主要有以下两点: ● 可 ...

  2. 【Excel】VBA编程 02 访问MySQL数据库

    1.配置Windows连接驱动ODBC 因为是访问MySQL,则对应的ODBC驱动由MySQL厂商发布 https://dev.mysql.com/downloads/connector/odbc/ ...

  3. 【VMware】将NAT虚拟机开放访问

    NAT模式下面需要将主机内的虚拟机提供给外部访问 这个设置可以通过开启端口来实现外部访问NAT虚拟机 主机端口 - 映射 虚拟机 IP 的端口,问题是有多少个虚拟机应用就需要开多少个端口...

  4. Jupyter Lab和Jupyter Notebook的区别

    JupyterLab与Jupyter Notebook:详细比较 简介 Jupyter Notebook是一个开源的Web应用程序,允许用户创建和共享包含实时代码.方程.可视化和解释性文本的文档.Ju ...

  5. DirectX9(D3D9)游戏开发:高光时刻录制和共享纹理的踩坑

    共享纹理 老游戏使用directx9无法直接与cc高光sdk(d3d11)对接,但是d3d9ex有共享纹理,我们通过共享纹理把游戏画面共享给cc录制,记录一些踩坑的笔记. 共享纹理示例: // 初始化 ...

  6. batch normalization的multi-GPU版本该怎么实现? 【Tensorflow 分布式PS/Worker模式下异步更新的情况】

    最近由于实验室有了个AI计算平台,于是研究了些分布式和单机多GPU的深度学习代码,于是遇到了下面的讨论: https://www.zhihu.com/question/59321480/answer/ ...

  7. 安装python库roboschool运行报错:ImportError: libpcre16.so.3: cannot open shared object file——解决方法

    如题: 运行roboschool运行报错. 操作系统: Ubuntu ImportError: libpcre16.so.3: cannot open shared object file: No s ...

  8. Mongolia地区民间风俗的一些理解

    声明:本文的内容为自己学习历史后的一些个人理解,其中内容的真实性并未考证. 总所周知,Mongolia地区有内外之分现在,但是以前均为我国领土,后来由于种种历史原因导致外Mongolia分离了出去,这 ...

  9. tensorflow1.x——如何在python多线程中调用同一个session会话

    如何在python多线程中调用同一个session会话? 这个问题源于我在看的一个强化学习代码: https://gitee.com/devilmaycry812839668/scalable_age ...

  10. 牛客周赛 Round 7

    牛客周赛 Round 7 A-游游的you矩阵_牛客周赛 Round 7 (nowcoder.com) 把四种字符凑一起看看有没有\(y,o,u\)就行 #include <bits/stdc+ ...