当前位置: 首页 > ai >正文

浏览器中 SignalR 连接示例及注意事项

官方文档地址:

ASP.NET Core SignalR configuration | Microsoft Learn

注意事项:

1. 浏览器中websocket 不支持自定义请求头, 如果需要自定义请求头, 只能使用 http 方式, 对应配置项: withUrl 第二个参数中增加 transport: SignalR.HttpTransportType.LongPolling 配置

.withUrl(`/ProductClientMsgHub}`, {transport: SignalR.HttpTransportType.LongPolling, // 使用 LongPolling headers: defaultHeaders,})

2. token 携带可以使用官方推荐的 accessTokenFactory

.withUrl(`/ProductClientMsgHub}`, {skipNegotiation: true,transport: SignalR.HttpTransportType.WebSockets, accessTokenFactory: () => util.cookies.get('token'), // 自动附加 Authorization Bearer})

3. withUrl 可以使用的配置项

示例代码:

import * as SignalR from "@microsoft/signalr";
import { Notification } from "element-ui";
import util from "@/libs/util.js";
import store from "@/store/index";let connection = null;
const baseUrl = '192.168.x.x:xxxx'// 创建连接
const createConnection = (headers = {}) => {// 设置连接头信息const defaultHeaders = {'LineId': headers.LineId || '','OperationId': headers.OperationId || '','ClientType': headers.ClientType || 'PC','OrganizeId': headers.OrganizeId || Number(localStorage.getItem('organizeId')),'Authorization': `Bearer ${util.cookies.get('token')}`}console.log('创建连接,headers:', defaultHeaders)connection = new SignalR.HubConnectionBuilder().configureLogging(SignalR.LogLevel.Information).withUrl(`${baseUrl}/ProductClientMsgHub?LineId=${headers.LineId}&OperationId=${headers.OperationId}&ClientType=${headers.ClientType}&OrganizeId=${headers.OrganizeId}`, {skipNegotiation: true, // 跳过协商transport: SignalR.HttpTransportType.WebSockets,  // transport: SignalR.HttpTransportType.LongPolling,withCredentials: true,// headers: defaultHeaders,accessTokenFactory: () => util.cookies.get('token'), // 自动附加 Authorization Bearer}).withAutomaticReconnect({nextRetryDelayInMilliseconds: () => {return 5000; // 每5秒重连一次},}).build();connection.keepAliveIntervalInMilliseconds = 15 * 1000; // 心跳检测15sconnection.serverTimeoutInMilliseconds = 30 * 60 * 1000; // 超时时间30m// 断开连接connection.onclose(async (error) => {console.log('SignalR 连接断开')if (error) {console.error('断开原因:', error)}})// 重连中connection.onreconnecting((error) => {console.log('SignalR 正在重连...')if (error) {console.error('重连原因:', error)}Notification({title: "提示",message: "服务器已断线,正在重连...",type: "warning",position: "bottom-right",})})// 重连成功connection.onreconnected((connectionId) => {console.log('SignalR 重连成功!')console.log('新的连接ID:', connectionId)Notification({title: "提示",message: "服务器重连成功",type: "success",position: "bottom-right",})})return connection;
}// 启动连接
const startConnection = async (headers = {}) => {try {// 如果连接不存在或已断开,创建新连接if (!connection || connection.state === SignalR.HubConnectionState.Disconnected) {console.log('正在连接 SignalR 服务...', headers)connection = createConnection(headers)await connection.start()console.log('SignalR 连接成功!')console.log('连接状态:', connection.state)console.log('连接ID:', connection.connectionId)return connection} else {console.log('当前连接状态:', connection.state)return connection}} catch (err) {console.error('SignalR 连接失败:', err)console.error('错误详情:', {message: err.message,stack: err.stack})}
}// 获取连接实例
const getConnection = () => {if (!connection) {console.warn('SignalR 连接未创建,请先调用 startConnection')return null}return connection
}export { getConnection as signalR, startConnection };

最终效果:

http://www.xdnf.cn/news/12972.html

相关文章:

  • 信创领域下的等保合规建设及解读
  • ava多线程实现HTTP断点续传:原理、设计与代码实现
  • 大学生职业发展与就业创业指导教学评价
  • 用 FFmpeg 实现 RTMP 推流直播
  • ArcGIS Pro裁剪栅格影像
  • 洞见未来医疗:RTC技术如何重塑智慧医疗新生态
  • __VUE_PROD_HYDRATION_MISMATCH_DETAILS__ is not explicitly defined.
  • android RecyclerView 加载不同的item
  • 基于STM32物联网智能鱼缸智能家居系统
  • Android Framework 之 AudioDeviceBroker
  • 关于TFLOPS、GFLOPS、TOPS
  • 高等三角函数大全
  • 基于Flask,MySQL和MongoDB实现的在线阅读系统
  • (每日一道算法题)子集
  • day51 python CBAM注意力
  • 当文化遇见科技:探秘国际数字影像创新生态高地
  • python爬虫——气象数据爬取
  • 了解Android studio 初学者零基础推荐(4)
  • LangChain + LangSmith + DeepSeek 入门实战:构建代码生成助手
  • 深入理解 React 样式方案
  • VRRP(虚拟路由冗余协议)深度解析
  • 循环语句之while
  • Netty自定义协议解析
  • R语言速释制剂QBD解决方案之一
  • vue3 daterange正则踩坑
  • c++第七天--继承与派生
  • 最好的无线麦克风是那款?2025硬核测评西圣和飞利浦无线领夹麦克风
  • 电子电气架构 --- E/E架构战略
  • 【高性能计算】java连接slurm提交作业,展示作业队列等
  • 【大厂机试题解法笔记】矩阵匹配