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();
相关推荐
云和数据.ChenGuang1 分钟前
vue中构建脚手架
前端·javascript·vue.js
千与千寻酱7 分钟前
排列与组合在编程中的实现:从数学概念到代码实践
前端·python
朱昆鹏19 分钟前
如何通过sessionKey 登录 Claude
前端·javascript·人工智能
wdfk_prog20 分钟前
klist 迭代器初始化:klist_iter_init_node 与 klist_iter_init
java·前端·javascript
cjinhuo22 分钟前
标签页、书签太多找不到?AI 分组 + 拼音模糊搜索,开源插件秒解切换难题!
前端·算法·开源
小章鱼学前端22 分钟前
小程序中使用 Iconfont 图标的优化指南
前端
一心只读圣贤书27 分钟前
解决jinkins的CI、CD使用非root执行sudo命令时无密码权限导致报错的问题
前端
携欢38 分钟前
POrtSwigger靶场之CSRF where token validation depends on token being present通关秘籍
前端·csrf
weixin_4462608539 分钟前
MudBlazor:轻松构建美观的Web应用程序!
前端
谜亚星43 分钟前
GSAP学习(五)
前端·动效