1、 新建.net core MVC项目,并引入nuget包
2、 添加客户端库
3、 修改startUp.cs文件,增加services.AddSignalR();和endpoints.MapHub<ServerHub>("/serverHub");
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.AddControllersWithViews(); 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"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapHub<ServerHub>("/serverHub"); }); } }
4、 新增ServerHub类
public class ServerHub:Hub { public async Task Send(string message) { await Clients.All.SendAsync("sendMessage", message); } }
5、 在Home/index.cshtml文件中加入如下的代码
@{ ViewBag.Title = "聊天窗口"; } <h2>Chat</h2> <div class="container"> <input type="text" id="message" /> <input type="button" id="sendmessage" value="Send" /> <input type="hidden" id="displayname" /> <ul id="discussion"></ul> </div> @section scripts { <!--引用SignalR库. --> <script src="~/lib/signalr/signalr.min.js"></script> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> <script> $(function () { let hubUrl = 'https://localhost:44360/serverHub'; let hubConnection = new signalR.HubConnectionBuilder().withUrl(hubUrl).build(); $('#sendmessage').click(function () { hubConnection.invoke("Send", $('#message').val()); // 清空输入框信息并获取焦点 $('#message').val('').focus(); }); //服务器回调方法 hubConnection.on("sendMessage", function (data) { // 向页面添加消息 $('#discussion').append('<li><strong>' + htmlEncode(data) + '</strong></li>'); }) hubConnection.start(); }); // 为显示的消息进行Html编码 function htmlEncode(value) { var encodedValue = $('<div />').text(value).html(); return encodedValue; } </script> }
6、 运行效果