填坑避雷真君之——.NET5 + VUE使用SinalR实现前后端通讯
时间:2021-01-04 10:38:54
收藏:0
阅读:0
本文旨在节约时间,避免查阅资料和踩坑耗费太多时间,如果你只想快速整活,那看这个就对了。
1、.NET5后端部分
1.1首先引入包
Install-Package Microsoft.AspNetCore.SignalR
1.2创建SingalR中心
using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace SignalRChat.Hubs { public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } } }
1.3配置SingalR
using SignalRChat.Hubs; namespace SignalRChat { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints => { //官网原Demo //endpoints.MapHub<ChatHub>("/chathub"); //根据大佬文章的经验,假如是前后端分离的情况,使用下面这个路由规则就对了 endpoints.MapHub<ChatHub>("/api/chatHub"); }); } } }
1.4后端发送消息示例
public class SignalRController { IHubContext<ChatHub> _hubContext; public SignalRController(IHubContext<ChatHub> hubContext){ _hubContext = hubContext; } public async Task Foo(){ // 发送给所有连接上的客户端 await _hubContext.Clients.All.SendAsync("ReceiveMessage", "张三", "想我了吗?"); } }
OK,后端结束。
2、VUE前端部分
2.1、引入signalR包
npm install @aspnet/signalr
2.2、在页面上import
import * as signalR from ‘@aspnet/signalr‘
2.3、添加代码
created() { // 1、创建连接对象 this.connection = new signalR.HubConnectionBuilder( // 配置通道路由 .withUrl(‘/api/chatHub‘) // 日志信息 .configureLogging(signalR.LogLevel.Information) .build() // 2、开始通讯 this.connection.start().then(function () { console.log(‘连接成功!‘) }).catch(function (err) { console.log(‘连接失败!‘ + err) }); // 3、订阅接收,ReceiveMessage为后端发送消息时写名称,必须一一对应 this.connection.on(‘ReceiveMessage‘, function (user, message) { console.log(`成功接收消息!user:${user},message:${message}}}`) // 接收到消息后你想做的事就写在这里 }); }, methods: { call(){ // 4、呼叫后端 this.connection.invoke(‘ReceiveMessage‘, ‘张三‘,‘三儿,你还好吗?‘).catch(function (err) { return console.error(err); }); } }
OK,前端结束
3、部署到Nginx
需要对nginx配置进行如下配置,否则会报错
proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $http_connection;
4、测试吧
本文没有记录一些高级功能,如:对单点发送,对群组发送,客户端断线重连等。
当然不是因为笔者懒,常言道万事开头难,之后更难,笔者肯定不是因为怕麻烦,怕难。
相信上面一套连招跑通的话,后面的都不是什么事儿了,加油吧诸君!
感谢提供宝贵经验的大佬们!
巨人的肩膀:
https://www.cnblogs.com/laozhang-is-phi/p/netcore-vue-signalr.html#tbCommentBody
评论(0)