前端vue中使用signalr的方法举例详解_vue.js
这一步需要指定SignalR Hub的URL。
在使用 SignalR 的 HubConnectionBuilder 时,可以通过链式方法配置连接的各个参数。以下是完整的参数配置写法和说明:
const connection = new signalR.HubConnectionBuilder() // 必填:设置 Hub 的 URL .withUrl(url, options) // 可选:配置日志 .configureLogging(logging) // 可选:配置自动重连 .withAutomaticReconnect(retryPolicy) // 可选:配置自定义 HTTP 客户端 .withHubProtocol(protocol) // 构建连接对象 .build();
.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,})
// 简单配置日志级别.configureLogging(signalR.LogLevel.Information)// 自定义日志记录器.configureLogging({ log(logLevel, message) { console.log(`[SignalR] ${logLevel}: ${message}`); }})
// 默认策略:重试 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; // 停止重连 }})
// 使用 MessagePack 二进制协议.withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol())// 自定义协议(需实现 IHubProtocol)
.withUrl(url, { withCredentials: true })
根据实际需求选择配置项,确保兼容 SignalR 客户端库的版本。
启动连接是指让前端与SignalR Hub建立实际的连接。
客户端方法是指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 实现连接、发送和接收数据的完整案例,包含详细注释和关键配置:
在 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 连接已关闭') } }}
// 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 跨域问题:确保服务端启用 CORS: services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader())); 身份验证:如果使用 JWT,需在 .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 }) 通过这个案例,你可以快速实现: 到此这篇关于前端vue中使用signalr的文章就介绍到这了,更多相关前端vue使用signalr内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!withUrl 配置中传递 Token:
本文地址: https://www.earthnavs.com/jishuwz/d903e5ee85cb73d7c36c.html




















