Web实时通讯@microsoft/signalr

[复制链接]
发表于 2025-12-18 14:41:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
概要分析

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

  • build() 与后端signalR服务创建链接;
  • 利用 on 方法监听后端界说的函数;ps:由后端发起,后端向前端发送数据
  • 利用 invoke 自动触发后端的函数;ps:由前端发起,前端向后端发送哀求
安装依靠
  1. pnpm install @microsoft/signalr --save
复制代码
组件封装
  1. import * as signalR from "@microsoft/signalr";
  2. const serverUrl = "https://youraddress";
  3. class WebSocketManager {
  4.     constructor() {
  5.         this.connection = null;
  6.         this.connectionStatus = 'disconnected';
  7.     }
  8.     createWebSocket(fileId) {
  9.         this.connectionStatus = 'connecting';
  10.         return new Promise((resolve, reject) => {
  11.             try {
  12.                 this.connection = new signalR.HubConnectionBuilder()
  13.                     .withAutomaticReconnect()//断线自动重连
  14.                     .withUrl(`${serverUrl}?fileId=${fileId}`)
  15.                     .build();
  16.                 //启动连接
  17.                 this.connection.start().then(() => {
  18.                     console.log("SignalR server 连接成功");
  19.                     this.connectionStatus = 'connected';
  20.                     resolve(this.connectionStatus);
  21.                 }).catch((err) => {
  22.                     this.connectionStatus = 'error'
  23.                     console.error("SignalR server 连接失败", err);
  24.                     reject(err);
  25.                 });
  26.             } catch (error) {
  27.                 console.error('Failed to start connection:', error);
  28.                 this.connectionStatus = 'error';
  29.                 reject(err);
  30.             }
  31.         });
  32.     }
  33.     //获取状态
  34.     getConnectionStatus() {
  35.         return this.connectionStatus;
  36.     }
  37.     //获取连接对象
  38.     getConnection() {
  39.         return this.connection;
  40.     }
  41.     //断开连接
  42.     stopWebSocket() {
  43.         if (this.getConnectionStatus() === 'connected') {
  44.             this.connection.stop().then(() => {
  45.                 this.connectionStatus = 'disconnected';
  46.                 console.log("SignalR server 连接断开");
  47.             }).catch((err) => {
  48.                 console.error("SignalR server 连接断开失败", err);
  49.             });
  50.         }
  51.     }
  52.     //发送消息
  53.     sendMsg(msg) {
  54.         if (this.getConnectionStatus() !== 'connected') {
  55.             return console.error("SignalR server 未连接,无法发送消息");
  56.         }
  57.         this.connection.invoke("SendMessage", msg).catch((err) => {
  58.             console.error("SignalR server 发送消息失败", err);
  59.         });
  60.     }
  61.     //监听消息
  62.     // receiveMsg() {
  63.     //     return new Promise((resolve, reject) => {
  64.     //         // console.log("receiveMsg=======>FileProcess");
  65.     //         this.connection.on("HeartBeat", (msg) => {
  66.     //             console.log("接收消息成功========>", msg);
  67.     //             resolve(msg);
  68.     //         })
  69.     //     })
  70.     // }
  71. }
  72. export default new WebSocketManager();
复制代码
利用案例
  1. // 使用示例
  2. const signalRService = new SignalRService('链接地址');
  3. signalRService.start()
  4.   .then(() => console.log('SignalR service started'))
  5.   .catch(error => console.error('Failed to start SignalR service:', error));
  6. // 在需要的时候发送消息
  7. signalRService.send('Hello, SignalR!')
  8.   .then(() => console.log('Message sent'))
  9.   .catch(error => console.error('Failed to send message:', error));
  10. // 接收消息
  11. signalRService.receiveMessage((message: string) => {
  12.   console.log("Received message:", message);
  13. }, "后端定义的方法名称(获取由后端给前端发送的数据)")
  14. // 停止连接
  15. signalRService.stop();
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表