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();
相关推荐
一 乐8 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
C_心欲无痕8 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
清沫9 小时前
Claude Skills:Agent 能力扩展的新范式
前端·ai编程
yinuo9 小时前
前端跨页面通信终极指南:方案拆解、对比分析
前端
yinuo10 小时前
前端跨页面通讯终极指南⑨:IndexedDB 用法全解析
前端
xkxnq10 小时前
第二阶段:Vue 组件化开发(第 16天)
前端·javascript·vue.js
烛阴10 小时前
拒绝配置地狱!5 分钟搭建 Three.js + Parcel 完美开发环境
前端·webgl·three.js
xkxnq11 小时前
第一阶段:Vue 基础入门(第 15天)
前端·javascript·vue.js
anyup12 小时前
2026第一站:分享我在高德大赛现场学到的技术、产品与心得
前端·架构·harmonyos
BBBBBAAAAAi12 小时前
Claude Code安装记录
开发语言·前端·javascript