asp.net core 3.0 使用SignalR
废话不多说,直接上操作清单:
1、建立Asp.net core 3.0项目。步骤省略
2、添加引用Microsoft.AspNetCore.SignalR 直接使用Nuget添加
3、添加类文件ChatHub继承Hub(中心)。代码如下:
using Microsoft.AspNetCore.SignalR; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SignalRDemo.Models { /// <summary> /// 中心类 /// </summary> public class ChatHub: Hub { /// <summary> /// 客户端调用方法 /// </summary> /// <param name="data"></param> /// <returns></returns> public Task SendMessage(ChatMessageInfo data) { //服务端返回是调用方法 return Clients.All.SendAsync("ReceiveMessage", data); } public Task SendMessageToCaller(string message) { return Clients.Caller.SendAsync("ReceiveMessage", message); } public Task SendMessageToGroup(string message) { return Clients.Group("SignalR Users").SendAsync("ReceiveMessage", message); } } }
ChatMessageInfo 类:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SignalRDemo.Models { public class ChatMessageInfo { public string UserName { get; set; } public string Message { get; set; } } }
4、修改配置Startup,红色字体是新增项
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SignalRDemo.Models; namespace SignalRDemo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddControllersWithViews();
//运行跨域配置 services.AddCors(options => options.AddPolicy("CorsPolicy", builder => { builder.AllowAnyMethod().AllowAnyHeader() .WithOrigins("http://localhost:54916") .AllowCredentials(); })); services.AddSignalR(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseCors("CorsPolicy"); app.UseEndpoints(endpoints => { endpoints.MapHub<ChatHub>("/ChatHub"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
5、添加SignalR.js. Vs右键项目/添加/客户端库
步骤2:
最终目录生产文件:
6、编写html页面、我就网上Copy一个测试
@{ ViewData["Title"] = "测试SignalR"; } <div class="text-center"> <ul class="form-group" id="messagesListUl" style="margin-bottom:20px"></ul> <form> <div class="form-group"> <label for="username">key:</label> <input type="text" class="form-control" id="username" name="username"> </div> <div class="form-group"> <label for="msgcontent">Value:</label> <textarea rows="5" cols="20" id="msgcontent" name="msgcontent" class="form-control"></textarea> </div> <input type="button" onclick="btnSendMsg()" value="发送"> </form> </div> <script type="text/javascript" src="~/lib/signalr/dist/browser/signalr.min.js"></script> <script> const connection = new signalR.HubConnectionBuilder() .withUrl("/ChatHub") .configureLogging(signalR.LogLevel.Information) .build(); connection.start().then(function(){ console.log("连接成功"); }).catch(function(ex){ console.log("连接失败"+ex); //SignalR JavaScript 客户端不会自动重新连接,必须编写代码将手动重新连接你的客户端 setTimeout(() => start(), 5000); }); async function start() { try { await connection.start(); console.log("connected"); } catch (err) { console.log(err); setTimeout(() => start(), 5000); } }; connection.onclose(async () => { start(); }); //绑定事件("ReceiveMessage"和服务器端的SendMessage方法中的第一个参数一致) //服务器端调用客户端 connection.on("ReceiveMessage", function (data) { alert("返回"); const li = document.createElement("li"); li.innerText = data.userName + " : " + data.message; document.getElementById("messagesListUl").appendChild(li); }); //调用服务器端 function btnSendMsg() { alert(11); var UserName = $.trim($("#username").val()); var Message = $.trim($("#msgcontent").val()); connection.invoke("SendMessage", {UserName,Message}).catch(err => console.error("发送失败:"+err.toString())); } </script>
最终一切顺利。希望能帮助到大家