Bootstrap

Web实时通信@microsoft/signalr

概要说明

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

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

安装依赖

pnpm install @microsoft/signalr --save

组件封装

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;

使用案例

// 使用示例
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();
;