当前位置:网站首页>ASP. Net core signalr series hub tutorial
ASP. Net core signalr series hub tutorial
2022-06-30 15:40:00 【zhoubangbang1】
The content of this article is
What is? SignalR center
To configure SignalR
Create and use SignalR
Send a message to the client
Strong type center
1. SignalR center
utilize SignalR, You can call methods from the server to the linked client . Define the method called by the client on the server ; Define the method to be called for the service on the client side .SignalR Responsible for making real-time client-to-server and server-to-client communication possible .
2. To configure SignalR
SignalR Middleware requires some services , These services call services.AddSignalR In progress Startup Of ConfigureServices Perform registration configuration
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod().AllowAnyHeader()
.WithOrigins("http://localhost:51617")
.AllowCredentials();
}));
services.AddSignalR();// register SignalR service
} take SignalR Features added to ASP.NET Core Application time , Please be there. Startup.Configure Call in method app.UseSignalR To set up SignalR route .
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSignalR(routes =>
{
routes.MapHub<StronglyTypedChatHub>("/chatHub");
});
app.UseCors("CorsPolicy");
app.UseMvc();
}3. Create and use SignalR
public class ChatHub : Hub
{
public Task SendMessage(string user, string message)
{
return Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
You can specify the return type and parameters ( Including complex types and arrays ), Like in any C# In the same way . SignalR Handle serialization and deserialization of complex objects and arrays in parameters and return values .
notes :
The center is temporary :
Do not store state in hub In the properties of class . Each central method call is executed on a new central instance .
When calling an asynchronous method that relies on the hub to remain active , Please use await. for example , If there is no await Called in the case of , Then the method ( Such as Clients.All.SendAsync(...)) May fail .
for example : stay ChatHub Add a list to _ ConnectionId, Use and obtain by SignalR The only connection assigned ID. Each connection has a connection ID.
public class ChatHub : Hub
{
public static List<string> _connectionId = new List<string>();
public Task SendMessage(string user, string message)
{
_connectionId.Add(Context.ConnectionId);
return Clients.All.SendAsync("ReceiveMessage", user, message, string.Join("#",_connectionId));
}
}

From the picture we find _connectionId There is always only one number stored in the client that is currently clicked ConnectionId This is because Each central method call is executed on a new central instance
If you create a static class :
public static class staticClass
{
public static List<string> connectionId = new List<string>();
}
public class ChatHub : Hub
{
public Task SendMessage(string user, string message)
{
staticClass.connectionId.Add(Context.ConnectionId);
if (staticClass.connectionId.Count >1)
{
/// Randomly generated index
Random r1 = new Random();
int index = r1.Next(0, staticClass.connectionId.Count);
return Clients.Client(staticClass.connectionId[index]).SendAsync("ReceiveMessage", user, message, Context.ConnectionId, Context.UserIdentifier);
}
else
{
return Clients.All.SendAsync("ReceiveMessage", user, message, Context.ConnectionId, Context.UserIdentifier);
}
}
}Rerun program , Get the results :

4. Strong type center
advantage : Strongly typed Hub You can avoid magic function names , It's easier to maintain and find problems than weak types , Go straight to the code
shortcoming : More code writing
Specific steps :
1. Use Hub<T> Strong typing Hub Instead of SendAsync Method .
The method called by the server-side link client will be extracted to IChatClient Interface , It's actually going to be ChatHub Using strings to call client methods , Abstract as an interface .
public interface IChatClient
{
Task ReceiveMessage(string user, string message);
}
2. Implementation interface Refactor the previous ChatHub Example
public class StronglyTypedChatHub: Hub<IChatClient>
{
public async Task SendMessage(string user, string message)
{
staticClass.connectionId.Add(Context.ConnectionId);
if (staticClass.connectionId.Count > 1)
{
/// Randomly generated index
Random r1 = new Random();
int index = r1.Next(0, staticClass.connectionId.Count);
await Clients.Client(staticClass.connectionId[index]).ReceiveMessage( user, message, Context.ConnectionId);
}
else
{
await Clients.All.ReceiveMessage( user, message, Context.ConnectionId);
}
}
}3. take Configur The routing
The original
app.UseSignalR(route =>
{
route.MapHub<StronglyTypedChatHub>("/chathub");
});
Turn into :
app.UseSignalR(route =>
{
route.MapHub<StronglyTypedChatHub>("/chathub");
});
This is my wechat public number , I hope to grow up with you , I will keep it updated once a day or so .

边栏推荐
- Notes on zero basic C language learning -- first introduction -- 1 notes that mom can understand
- 1058 a+b in Hogwarts (20 points)
- Single cycle CPU of the design group of West University of Technology
- from Crypto. Cipher import AES could not find the solution record with module error
- Joint examination for management -- sample composition
- 【Leetcode】链表排序(逐步提高时空复杂度)
- Management joint examination - mathematical formula
- It's so brain - burning that no wonder programmers lose their hair
- The crystal ball "data insight" was officially launched: insight into the change of consumption trend and the details of interactive experience
- 1077 kuchiguse (20 points)
猜你喜欢

The principle of fluent 2 rendering and how to realize video rendering

How to do a good job in high concurrency system design? I have summarized three points

Oracle中的With As 子查询

Rte2021 review of the practice and the way of AI OPS landing

Explain service idempotency design in detail

Compare whether the two arrays are the same

终于看懂科学了!200张图领略人类智慧的巅峰

How to browse mobile web pages on your computer

Anyrtc implements application scenarios based on webrtc

消息队列十连问
随机推荐
1062 talent and virtue (25 points)
How should we understand the variability of architecture design?
Kubernetes: a comprehensive analysis of container choreography
Industry analysis | the future of real-time audio and video
数数据可视化实战案例(timeline轮播图,streamlit 控件年份 metabase可视化使用教程)2.0
NPM install --global --save --save dev differences
Curl: (23) failed writing body (1354 i= 1371) problem solving method
Scattered knowledge of C language (unfinished)
Chapter III installation and use of jupyter
How to do a good job in high concurrency system design? I have summarized three points
Flask Sqlalchemy - automatically export the table model (flask sqlacodegen) & no single primary key problem ---orm (8)
G - building a space station
1105 spiral matrix (25 points)
Single cycle CPU of the design group of West University of Technology
1082 read number in Chinese (25 points)
Xiao Sha's pain (thinking problem)
1019 general palindromic number (20 points)
Summary of system stability construction practice
Technology sharing | anyrtc service single port design
Infrastructure is code. What are you talking about?