1、asp.net core使用signalR入門html
1,nuget Microsoft.AspNetCore.SignalR 前端
2,新建ChatHub文件node
using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace SignalRDemo { public class ChatHub:Hub { public async Task SendMessage(string user,string message) { await Clients.All.SendAsync("ReceiveMessage",user,message); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.SignalR; 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.AddMvc(); services.AddSignalR(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseSignalR(routes=>{ routes.MapHub<ChatHub>("/chathub"); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
3,生成signalr.js文件jquery
使用npm下載signalr D:\signalr> npm install @aspnet/signalr npm
將 D:\signalr\node_modules\@aspnet\signalr\dist\browser\signalr.js 拷貝到項目中 SignalRDemo\wwwroot\lib\signalr\signalr.js 後端
4,在視圖頁面使用服務器
@{ ViewData["Title"] = "Home Page"; } <input type="text" name="" id="message" class="form-control" value="" required="required" pattern="" title=""> <button type="button" class="btn btn-default" id="send" >發送</button> <div id="content"></div> @section Scripts{ <script src="~/lib/signalr/signalr.js"></script> <script> const connection=new signalR.HubConnectionBuilder() .withUrl("/chatHub") .build(); connection.on("ReceiveMessage",(use,message)=>{ $("#content").append(message+"<br/>"); }); connection.start().catch(err=>{alert(err)}); $("#send").click(function(){ var msg= $("#message").val(); connection.invoke("SendMessage","",msg).catch(err=>{alert(err)}) }); </script> }
案例下載:https://pan.baidu.com/s/1FEgPEbPZOribtYnLv-XCNQapp
2、先後端分離模式cors
1,前端代碼asp.net
<html> <head> <title></title> </head> <body> <input type="text" name="" id="message" class="form-control" value="" required="required" pattern="" title=""> <button type="button" class="btn btn-default" id="send" >發送</button> <div id="content"></div> <script src="js/jquery.js" ></script> <script src="js/signalr.js"></script> <script> const connection=new signalR.HubConnectionBuilder() .withUrl("http://localhost:5000/chatHub") .build(); connection.on("ReceiveMessage",(use,message)=>{ $("#content").append(message+"<br/>"); }); connection.start().catch(err=>{alert(err)}); $("#send").click(function(){ var msg= $("#message").val(); connection.invoke("SendMessage","",msg).catch(err=>{alert(err)}) }); </script> </body> </html>
使用npm下載signalr
2,後端須要配置cors
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.SignalR; 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.AddMvc(); //註冊Cors的策略 services.AddCors(options=>options.AddPolicy("CorsPolicy",builder=>{ builder.AllowAnyMethod() .AllowAnyHeader() .AllowAnyOrigin() .AllowCredentials(); })); services.AddSignalR(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); //使用CorsPolicy策略的Cors app.UseCors("CorsPolicy"); app.UseSignalR(routes=>{ routes.MapHub<ChatHub>("/chathub"); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace SignalRDemo { public class ChatHub:Hub { public async Task SendMessage(string user,string message) { await Clients.All.SendAsync("ReceiveMessage",user,message); } } }
案例下載:https://pan.baidu.com/s/1qcYOKuO42HltFmwP3vZgSA
3、Hub
1,建立並使用Hub
public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user,message); } public Task SendMessageToCaller(string message) { return Clients.Caller.SendAsync("ReceiveMessage", message); } public Task SendMessageToGroups(string message) { List<string> groups = new List<string>() { "SignalR Users" }; return Clients.Groups(groups).SendAsync("ReceiveMessage", message); } public override async Task OnConnectedAsync() { await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception exception) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnDisconnectedAsync(exception); } }
2,Clients對象
①每一個實例Hub
類有一個名爲Clients
包含服務器和客戶端之間通訊的如下成員:
屬性 | 描述 |
---|---|
All |
在全部鏈接的客戶端上調用方法 |
Caller |
調用 hub 方法在客戶端上調用方法 |
Others |
除調用的方法的客戶端的全部鏈接客戶端上調用方法 |
此外,Hub.Clients
包含如下方法:
方法 | 描述 |
---|---|
AllExcept |
在指定的鏈接除外的全部鏈接的客戶端上調用方法 |
Client |
在特定鏈接的客戶端上調用方法 |
Clients |
在特定鏈接的客戶端上調用方法 |
Group |
將消息發送到指定的組中的全部鏈接 |
GroupExcept |
將消息發送到指定的組,除非指定鏈接中的全部鏈接 |
Groups |
將一條消息發送到多個組的鏈接 |
OthersInGroup |
將一條消息發送到一組的鏈接,不包括客戶端調用 hub 方法 |
User |
將消息發送到與特定用戶關聯的全部鏈接 |
Users |
將消息發送到與指定的用戶相關聯的全部鏈接 |
3,將消息發送到客戶端
//將消息發送到調用此hub的客戶端 public Task SendMessageToCaller(string message) { return Clients.Caller.SendAsync("ReceiveMessage", message); } //將消息發送到指定發送的全部客戶端 public Task SendMessageToGroups(string message) { List<string> groups = new List<string>() { "SignalR Users" }; return Clients.Groups(groups).SendAsync("ReceiveMessage", message); }
4,處理消息事件
//鏈接觸發 public override async Task OnConnectedAsync() { await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnConnectedAsync(); } //斷開鏈接觸發 public override async Task OnDisconnectedAsync(Exception exception) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnDisconnectedAsync(exception); }
5,客戶端處理錯誤
connection.invoke("SendMessage", user, message).catch(err => console.error(err));
4、客戶端調用hub
nuget Microsoft.AspNetCore.SignalR.Client
using System; using Microsoft.AspNetCore.SignalR.Client; using System.Threading.Tasks; using System.Threading; namespace SignalRClient { class Program { static void Main(string[] args) { Console.WriteLine("準備就緒..."); HubConnection connection=new HubConnectionBuilder() .WithUrl("http://localhost:5000/chatHub") .Build(); //鏈接hub connection.StartAsync(); Console.WriteLine("已鏈接"); //定義一個客戶端方法ReceiveMessage connection.On<string,string>("ReceiveMessage",(UriParser,message)=>{ Console.WriteLine($"接收消息:{message}"); }); while(true) { Thread.Sleep(1000); var msg=Console.ReadLine(); //發送給hub的SendMessage方法 connection.InvokeAsync("SendMessage","",msg); } } } }