Web实时通信@microsoft/signalr

概要说明

signalr 是微软对 websocket技术的封装;

  1. build() 与后端signalR服务建立链接;
  2. 使用 on 方法监听后端定义的函数;ps:由后端发起,后端向前端发送数据
  3. 使用 invoke 主动触发后端的函数;ps:由前端发起,前端向后端发送请求

安装依赖

bash 复制代码
pnpm install @microsoft/signalr --save

组件封装

javascript 复制代码
import { HubConnection, HubConnectionBuilder } from "@microsoft/signalr";

class SignalRService {
  private connection: HubConnection | null = null;
  private connectionStatus:
    | "disconnected"
    | "connecting"
    | "connected"
    | "error" = "disconnected";
  private serverUrl: string = ""; // 建立链接的服务器地址

  constructor(private url: string) {
    this.url = url;
  }

  public async start() {
    this.connectionStatus = "connecting";
    try {
      this.connection = new HubConnectionBuilder()
        .withAutomaticReconnect()//断线自动重连
        .withUrl(this.serverUrl + `?fileId=${this.url}`)
        .build();

      //启动连接
      await this.connection.start();
      this.connectionStatus = 'connected';
      console.log("SignalR server 连接成功");

    } catch (error) {
      console.error("SignalR server 连接失败:", error);
      this.connectionStatus = "error";
      throw error;
    }
  }

//断开服务链接
  public async stop() {
    try {
      if (this.connection) {
        await this.connection.stop();
        this.connectionStatus = "disconnected";
        console.log("SignalR 断开连接");
      }
    } catch (error) {
      console.log(error);
    }
  }

  //重新链接
  public async reconnect() {
    if (this.connection) {
      await this.connection.stop();
      await this.connection.start();
      console.log("SignalR 重连中");
    }
  }

  //接收消息(接收后端发送给前端的数据)
  public async receiveMessage(callback: (message: string) => void, eventName: string) {
    if (this.connection) {
      this.connection.on(eventName, (message: string) => {
        callback(message);
      });
    }
  }

//发送消息(由前端发送消息,后端接收数据)
  public async send(message: string) {
    if (this.connection && this.connectionStatus === "connected") {
      await this.connection.invoke("SendMessage", message);
    } else {
      throw new Error("Connection is not established");
    }
  }

//获取当前状态
  public get status() {
    return this.connectionStatus;
  }
  
  public getConnection() {
    return this.connection;
  }
}

export default SignalRService;

使用案例

javascript 复制代码
// 使用示例
const signalRService = new SignalRService('链接地址');
signalRService.start()
  .then(() => console.log('SignalR service started'))
  .catch(error => console.error('Failed to start SignalR service:', error));

// 在需要的时候发送消息
signalRService.send('Hello, SignalR!')
  .then(() => console.log('Message sent'))
  .catch(error => console.error('Failed to send message:', error));

// 接收消息
signalRService.receiveMessage((message: string) => {
  console.log("Received message:", message);
}, "后端定义的方法名称(获取由后端给前端发送的数据)")

// 停止连接
signalRService.stop();
相关推荐
try2find2 分钟前
打印ascii码报错问题
java·linux·前端
郑州光合科技余经理15 分钟前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
冰暮流星1 小时前
javascript事件案例-全选框案例
服务器·前端·javascript
Csvn2 小时前
前端性能优化实战指南
前端
Moment2 小时前
2026 年,AI 全栈时代到了,前端简历别再只写前端技术了 🫠🫠🫠
前端·后端·面试
糯米团子7492 小时前
Web Worker
开发语言·前端·javascript
freewlt2 小时前
React Server Components 深度解析
前端·react.js·前端框架
wordbaby2 小时前
一次跨端 Loading 卡死复盘:把请求计数从 Axios 拦截器迁到 try/catch/finally
前端·axios
我命由我123452 小时前
JavaScript 开发 - 获取函数名称、获取函数参数数量、获取函数参数名称
开发语言·前端·javascript·css·html·html5·js
IT_陈寒3 小时前
JavaScript里这个隐式类型转换的坑,我终于爬出来了
前端·人工智能·后端