当前位置:网站首页>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 .

边栏推荐
- On which platform is it safer to buy Treasury reverse repo?
- 4.7 type() function query data type
- G - navigation nightare
- Chapter III installation and use of jupyter
- 深入理解.Net中的线程同步之构造模式(二)内核模式1.内核模式构造物Event事件
- Create a new MySQL database under Linux and import SQL files
- Developer practice - the future of Agora home AI audio and video
- 各省GDP可视化案列,附带csv Metabase处理
- Flask-SQLAlchemy----sqlalchemy. exc.InvalidRequestError: SQL expression, column, or mapped e---ORM(9)
- 1031 Hello world for u (20 points)
猜你喜欢

The short video and live broadcast incubation training camp with goods opens nationwide enrollment!
![[matlab] 3D drawing summary](/img/57/05156340ccdd79b866c4df955b3713.jpg)
[matlab] 3D drawing summary

【时序数据库InfluxDB】Windows环境下配置InfluxDB+数据可视化,以及使用 C#进行简单操作的代码实例

Management joint examination - mathematical formula

linux下修改mysql密码: ERROR 1396 (HY000): Operation ALTER USER failed for ‘root‘@‘localhost‘

(Niuke) BFS

Npumcm selection question 3 and acmc2020a

It's so brain - burning that no wonder programmers lose their hair

Kubernetes: a comprehensive analysis of container choreography

Rte2021 review of the practice and the way of AI OPS landing
随机推荐
Visualization of provincial GDP with CSV metabase processing
Developer practice - the future of Agora home AI audio and video
消息队列十连问
Don't fight for big companies
数据治理市场:亿信华辰朝左,华傲数据向右
K - rochambau (joint search, enumeration)
【子矩阵数量统计】CF1181C Flag子矩阵数量统计
Operator%
It's so brain - burning that no wonder programmers lose their hair
Help you accumulate audio and video knowledge, Agora developer's roaming guide officially set sail
Anyrtc implements application scenarios based on webrtc
BYD is more and more like Huawei?
Web technology sharing | whiteboard toolbar encapsulation of Web
Fundamentals of C language -- similarities and differences between arrays and pointers
Summary of system stability construction practice
Three types of technical debt that programmers often encounter: code, data, and architecture
N - Is There A Second Way Left? (minimum spanning tree, Kruskal)
[sub matrix quantity statistics] cf1181c flag sub matrix quantity statistics
剑指 Offer II 080. 含有 k 个元素的组合 回溯
Zero basic C language learning notes -- first introduction -- 2 data types & variables and constants