前端vue中使用signalr的方法举例详解
作者:小芝麻咿呀
一、引入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) { return Math.random() * 1000; // 随机延迟 <1s } return null; // 停止重连 } })
4. withHubProtocol
- 作用:设置消息协议(默认为 JSON)。
- 参数:
.withHubProtocol(protocol: IHubProtocol)
- 示例:
// 使用 MessagePack 二进制协议 .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol()) // 自定义协议(需实现 IHubProtocol)
5. build
- 作用:生成最终的
HubConnection
实例。 - 示例:
.build();
完整示例
const connection = new signalR.HubConnectionBuilder() .withUrl("https://example.com/chathub", { transport: signalR.HttpTransportType.WebSockets, accessTokenFactory: () => localStorage.getItem("token"), skipNegotiation: true, headers: { "X-Client-Version": "1.0.0" } }) .configureLogging(signalR.LogLevel.Debug) .withAutomaticReconnect([0, 1000, 5000, 10000]) .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol()) .build(); // 启动连接 connection.start() .then(() => console.log("Connected!")) .catch(err => console.error("Connection failed:", err));
其他配置(通过 withUrl 的 options)
withCredentials
:跨域请求携带 Cookie。.withUrl(url, { withCredentials: true })
timeout
:设置单个 HTTP 请求超时时间。.withUrl(url, { timeout: 15000 }) // 15秒
根据实际需求选择配置项,确保兼容 SignalR 客户端库的版本。
三、启动连接
启动连接是指让前端与SignalR Hub建立实际的连接。
connection.start().then(() => { console.log("SignalR Connected."); }).catch(err => { console.error(err.toString()); });
四、定义客户端方法(客户端接收服务端信息)
客户端方法是指SignalR Hub调用时客户端执行的函数。通过这些方法,前端可以响应来自服务器的实时通知。
// 实时接收服务端信息(服务端-->客户端) connection.on('监听后端命名的方法A返回的数据:名称一般和invoke配套',(message) => { console.log('接受的信息Info message:', message); // 做一些赋值操作,把后端传来的数据渲染到页面 }); // 例: connection.on("ReceiveMessage", (user, message) => { const msg = `${user}: ${message}`; const li = document.createElement("li"); li.textContent = msg; document.getElementById("messagesList").appendChild(li); });
五、发送消息到服务器
前端可以通过调用SignalR Hub的方法来发送消息到服务器。通常,这些方法是用户操作(如点击按钮)触发的。
// 客户端与服务端进行沟通(客户端-->服务端),客户端调取后端的方法进行通讯,后端返回信息 connection.invoke("后端命名的方法A", "一些后端需要的变量根据自己需求填写") // 例: connection.invoke('SendData', 'Hello, SignalR!');
六、实际应用场景
实时聊天应用
使用SignalR最常见的场景之一就是实时聊天应用。通过SignalR,可以实现客户端之间的实时消息传递。实时数据更新
SignalR也可以用于实时数据更新,如股票行情、体育比赛比分等。这些应用需要频繁地从服务器获取最新数据,并实时更新到前端界面。通知系统
在一些应用中,当有新的事件发生时,需要实时通知用户。例如,在电商平台中,当有新的订单或者库存变化时,需要及时通知管理员。
七、完整案例
以下是一个在 Vue 3 中使用 SignalR 实现连接、发送和接收数据的完整案例,包含详细注释和关键配置:
1. 安装依赖
npm install @microsoft/signalr
2. 创建 SignalR 工具类(可选)
在 src/utils/signalR.js
中封装连接逻辑:
import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr' export default { // 创建连接 createConnection(url, options = {}) { return new HubConnectionBuilder() .withUrl(url, options) .withAutomaticReconnect([0, 2000, 10000, 30000]) // 自定义重连策略 .configureLogging(LogLevel.Information) .build() }, // 启动连接 async startConnection(connection) { try { await connection.start() console.log('SignalR 连接成功') return true } catch (err) { console.error('SignalR 连接失败:', err) return false } }, // 关闭连接 async stopConnection(connection) { if (connection) { await connection.stop() console.log('SignalR 连接已关闭') } } }
3. 在 Vue 组件中使用
<script> import signalR from '@/utils/signalR' // 导入工具类 export default { data() { return { connection: null, // SignalR 连接实例 message: '', // 输入框绑定的消息 messages: [], // 接收到的消息列表 hubUrl: 'https://your-api.com/chatHub' // Hub 地址 } }, mounted() { this.initializeConnection() }, beforeUnmount() { // 组件销毁前关闭连接 signalR.stopConnection(this.connection) }, methods: { // 初始化连接 async initializeConnection() { // 创建连接实例 this.connection = signalR.createConnection(this.hubUrl, { accessTokenFactory: () => localStorage.getItem('token') // 身份验证(可选) }) // 注册接收消息的回调 this.connection.on('ReceiveMessage', (user, message) => { this.messages.push({ user, message }) }) // 启动连接 const success = await signalR.startConnection(this.connection) if (!success) { alert('连接服务器失败,请检查网络') } // 监听连接关闭事件 this.connection.onclose(() => { console.log('连接已断开') }) }, // 发送消息 async sendMessage() { if (!this.message.trim()) return try { // 调用服务端 Hub 方法(假设方法名为 SendMessage) await this.connection.invoke('SendMessage', this.message) this.message = '' } catch (err) { console.error('发送消息失败:', err) alert('发送失败,请重试') } } } } </script> <template> <div> <h2>聊天室</h2> <div class="message-list"> <div v-for="(msg, index) in messages" :key="index"> <strong>{{ msg.user }}:</strong> {{ msg.message }} </div> </div> <input v-model="message" @keyup.enter="sendMessage" placeholder="输入消息" /> <button @click="sendMessage">发送</button> </div> </template>
4. 服务端代码(C# ASP.NET Core 示例)
// Hub 类 public class ChatHub : Hub { // 客户端调用此方法发送消息 public async Task SendMessage(string message) { // 广播消息给所有客户端(方法名 ReceiveMessage 需与前端匹配) await Clients.All.SendAsync("ReceiveMessage", Context.User.Identity.Name, message); } } // Startup.cs 或 Program.cs 中配置 app.UseEndpoints(endpoints => { endpoints.MapHub<ChatHub>("/chatHub"); });
关键注意事项
跨域问题:确保服务端启用 CORS:
services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()));
身份验证:如果使用 JWT,需在
withUrl
配置中传递 Token:.withUrl(this.hubUrl, { accessTokenFactory: () => localStorage.getItem('token') })
协议兼容:默认使用 JSON 协议,如需二进制优化可切换为 MessagePack:
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack' this.connection = new HubConnectionBuilder() .withHubProtocol(new MessagePackHubProtocol())
错误处理:建议全局监听错误:
this.connection.onreconnecting((error) => { console.log('正在尝试重新连接...', error) })
性能优化:在频繁通信场景下,建议使用 WebSocket 传输(需服务端支持):
.withUrl(url, { transport: HttpTransportType.WebSockets })
通过这个案例,你可以快速实现:
- SignalR 长连接管理
- 消息的发送和实时接收
- 自动重连和错误处理
- 与 Vue 3 生命周期的无缝集成
总结
到此这篇关于前端vue中使用signalr的文章就介绍到这了,更多相关前端vue使用signalr内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!