一、引入SignalR库
使用NPM引入SignalR库
npm install @microsoft/signalr
Js文件中引入
import * as signalR from '@microsoft/signalr';
二、初始化连接
这一步需要指定SignalR Hub的URL。
const connection = new signalR.HubConnectionBuilder()
.withUrl("https://yourserver.com/hub/myhub")
.build();
参数说明
在使用 SignalR 的 HubConnectionBuilder
时,可以通过链式方法配置连接的各个参数。以下是完整的参数配置写法和说明:
const connection = new signalR.HubConnectionBuilder()
// 必填:设置 Hub 的 URL
.withUrl(url, options)
// 可选:配置日志
.configureLogging(logging)
// 可选:配置自动重连
.withAutomaticReconnect(retryPolicy)
// 可选:配置自定义 HTTP 客户端
.withHubProtocol(protocol)
// 构建连接对象
.build();
1. withUrl
- 作用:设置 SignalR Hub 的 URL 和连接选项。
- 参数:
.withUrl(url: string, options?: IHttpConnectionOptions)
.withUrl("https://example.com/chathub", { transport: signalR.HttpTransportType.WebSockets | signalR.HttpConnectionOptions.LongPolling, // 自定义传输方式(默认为自动选择) accessTokenFactory: () => "your-access-token", // 身份验证 Token(如 JWT) httpClient: customHttpClient, // 自定义 HTTP 客户端(如修改超时时间) skipNegotiation: true, // 跳过协商步骤(仅适用于 WebSocket) headers: { "X-Custom-Header": "value" }, // 自定义请求头 // WebSocket 配置 websocket: { // 自定义 WebSocket 构造函数(如代理) constructor: CustomWebSocket, }, // 是否使用默认的 `fetch` API(默认为 true) useDefaultFetch: false, })
2. configureLogging
- 作用:配置日志级别或自定义日志记录器。
- 参数:
.configureLogging(logging: LogLevel | ILogger)
- 示例:
// 简单配置日志级别 .configureLogging(signalR.LogLevel.Information) // 自定义日志记录器 .configureLogging({ log(logLevel, message) { console.log(`[SignalR] ${ logLevel}: ${ message}`); } })
3. withAutomaticReconnect
- 作用:配置自动重连策略。
- 参数:
.withAutomaticReconnect(retryPolicy?: RetryPolicy)
// 默认策略:重试 0次、3次、10次、30次 后停止 .withAutomaticReconnect() // 自定义重试间隔数组(单位:毫秒) .withAutomaticReconnect([0, 2000, 5000, 10000, 30000]) // 高级策略:实现 `RetryPolicy` 接口 .withAutomaticReconnect({ nextRetryDelayInMilliseconds(retryContext) { if (retryContext.elapsedMilliseconds < 60000)<