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();
相关推荐
石小石Orz14 分钟前
浏览器的预检请求OPTIONS到底有什么用?
前端
落雪小轩韩18 分钟前
网格布局 CSS Grid
前端·css
parade岁月20 分钟前
Vue 3 父子组件模板引用的时序陷阱与解决方案
前端
xianxin_25 分钟前
CSS Outline(轮廓)
前端
moyu8425 分钟前
遮罩层设计与实现指南
前端
Pedantic34 分钟前
用 SwiftUI 打造一个 iOS「设置」界面
前端
timeweaver40 分钟前
深度解析 Nginx 前端 location 配置与优先级:你真的用对了吗?
前端·nginx·前端工程化
鲸落落丶41 分钟前
网络通信---Axios
前端
wwy_frontend43 分钟前
React性能优化实战:从卡顿到丝滑的8个技巧
前端·react.js
小高0071 小时前
面试官:npm run build 到底干了什么?从 package.json 到 dist 的 7 步拆解
前端·javascript·vue.js