当前位置:网站首页>『SignalR』. Net using signalr for real-time communication
『SignalR』. Net using signalr for real-time communication
2022-07-25 22:02:00 【Lao Chen chat architecture】

After reading this article, you can gain
- You will be right SignalR Have a preliminary understanding and experience
- For which scenarios SignalR And how to access
- SignalR Code entry level for Demo Actual case
- Thank you for your kind words + Collection , Avoid missing next time ~

List of articles

One 、 Concept
1 What is? SignalR?
ASP.NET Core SignalR It's an open source library , It can be used to simplify adding real-time data to applications Web function . real time Web The function enables server-side code to push content to the client .
2 Which scenarios are suitable for use SignalR?
- Applications that need real-time notification . Social networks 、 E-mail 、
Chat、 game 、 Travel alerts and many other applications require notifications . - Applications that require frequent updates from the server . Examples include games 、 Social networks 、 vote 、 The auction 、 Maps and GPS application .
- Dashboards and monitoring applications . Examples include corporate dashboards 、 Instant sales updates or travel alerts .
- Collaborative applications . Examples of collaborative applications include whiteboard applications and team meeting software .
SignalR Provides for creating server to client remote procedure calls (RPC) Of API. RPC From the server side .NET Core The code calls the function on the client . Provide multiple supported platforms , Each of these platforms has its own client SDK. therefore ,RPC The programming language invoked is different .
3 ASP.NET Core SignalR What are the features ?
- Automatically handle connection management .
- Send a message to all connected clients at the same time . For example, chat room .
- Send a message to a specific client or group of clients .
- Zoom it , To handle the increasing traffic .
- Source hosted on GitHub In the repository on SignalR.
4 SignalR What real-time communication technologies are supported ?
SignalR Support the following ways to realize real-time communication :
WebSockets: It's one in a single TCP A protocol for full duplex communication over a connection , Make the communication between server and browser easier , The server can actively send information .Server-Sent Events:SSE And WebSocket The effect is similar , It is to establish the communication channel between the browser and the server , Then the server pushes the information to the browser .WebSocket It's two-way , and SSE Is one-way .Long Polling( Long polling ) : It is the same as the traditional polling principle , But the server will not return response information every time , Only when there is data or timeout will it return , This reduces the number of requests .
SignalR
Automatic selectionThe best transmission method within the capabilities of the server and client .
You can also specify it manually .
5 In the server Hub What is it? ?
Hub yes SignalR A component of , It runs in ASP.NET Core In the application . So it is server-side
One classHub Use
RPCAccept the message from the client , You can also send messages to clients . So it's a communication Hub


Two 、.NET Server case
Create an empty one in advance .Net Core Web project
1 establish SignalR center
The center is a class , Used as a processing client - Advanced pipeline for server communication .
- establish Hubs Folder .
- stay Hubs In the folder , Use the following code to create ChatHub.cs file :
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace SignalRChat.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
2 To configure SignalR
- Note the following 1~3 The code of points is added to Startup.cs file .
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
// 1 Introduce namespace
using SignalRChat.Hubs;
namespace Cyf.SignalR
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration {
get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
// 2 Add service injection
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
// 3 Add service mapping
endpoints.MapHub<ChatHub>("/chatHub");
});
}
}
}
- The code for this server has been written , As shown in the figure, the following code has been changed


3、 ... and 、JavaScript client
1 Installation package
- Mode one : adopt Visual Studio Installation package
- stay “ Solution explorer ”> in , Right click on the item , And then choose “ add to ”“ Client library ”.
- stay “ Add Client Library ” In the dialog box , about “ Provider ”, choice “unpkg”.
- about “ library ”, Input @microsoft/[email protected]
- choice “ Select a specific file ”, an “dist/browser” Folder , And then choose signalr.js and signalr.js.
- take “ Target location ” Set to wwwroot/js/signalr/
- choice “ install ”

- Mode two : adopt npm Installation package
npm init -y
npm install @microsoft/signalr
2 Add client code
- Use the following code to replace
Pages/Index.cshtmlThe content in :
@page
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-2">User</div>
<div class="col-4"><input type="text" id="userInput" /></div>
</div>
<div class="row">
<div class="col-2">Message</div>
<div class="col-4"><input type="text" id="messageInput" /></div>
</div>
<div class="row"> </div>
<div class="row">
<div class="col-6">
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
Index Code interpretation :
- Create text boxes and... With names and message text “ Submit ” Button .
- Use id=“messagesList” Create a list , Used to display from SignalR Messages received by the center .
- Contains the SignalR And the script reference created in the next step chat.js Application code .
- stay wwwroot/js In the folder , Use the following code to create chat.js file :
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
var li = document.createElement("li");
document.getElementById("messagesList").appendChild(li);
// We can assign user-supplied strings to an element's textContent because it
// is not interpreted as markup. If you're assigning in any other way, you
// should be aware of possible script injection concerns.
li.textContent = `${
user} says ${
message}`;
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
JS Code interpretation :
- Create and start the connection .
- towards “ Submit ” Button to add a handler for sending messages to the center .
- Add a handler to the connection object to receive messages from the hub and add them to the list .
- Come here JS The client code is finished , The following two documents have been mainly modified


Four 、 effect
- Select any browser , Enter a name and message , And then choose “ Send a message ” Button .
- The name and message are immediately displayed on both pages .

边栏推荐
- 【饭谈】那些看似为公司着想,实际却让人无法理解的事(二:面试时的软素质“眼缘”)
- 开源的RSS订阅器FreshRSS
- 虚拟内存与磁盘
- Ability to choose
- Share | intelligent fire emergency management platform solution (PDF attached)
- Animation curves are used every day. Can you make one by yourself? After reading this article, you will!
- JMeter websocket接口测试
- jsp九大内置对象
- [fan Tan] after the arrival of Web3.0, where should testers go? (ten predictions and suggestions)
- Composition of dog food
猜你喜欢

What should I do if I encounter the problem of verification code during automatic testing?

Guiding principles of information security construction

Why do independent sellers like to do e-mail marketing? The original conversion rate can be improved so much!

Whether the five distribution methods will produce internal fragments and external fragments

Summary of function test points of wechat sending circle of friends on mobile terminal

关于接口测试你想知道的都在这儿了

【汇编语言01】基础知识

PE format: analyze and implement IATHOOK

【饭谈】那些看似为公司着想,实际却让人无法理解的事(二:面试时的软素质“眼缘”)

2 lines of code to generate a solid desktop background
随机推荐
少儿编程 电子学会图形化编程等级考试Scratch一级真题解析(判断题)2022年6月
LeetCode_ 93_ Restore IP address
Create EDA - why should I learn EDA
After 2 years of functional testing, I feel like I can't do anything. Where should I go in 2022?
如何实现一个App应用程序,限制用户时间使用?
文件无法保存(文件夹已损坏无法读取怎么办)
自动化测试岗花20K招人,到最后居然没一个合适的,招两个应届生都比他们强吧
Children's programming electronic society graphical programming level examination scratch level 1 real problem analysis (judgment question) June 2022
立创EDA——器件的创建01-电阻(二)
Origen foundation officially launched $ogy stacking, leading a new round of ecological benefits
[51nod1676 undirected graph isomorphism] undirected graph hash [easy to understand]
Pyg tutorial (8): calculate a more efficient sparse matrix form
Ansible+cronab batch deployment patrol
I/o case practice
Whether the five distribution methods will produce internal fragments and external fragments
立创EDA——我为什么要学EDA
c sqlite ... ...
Having met a tester with three years' experience in Tencent, I saw the real test ceiling
Jmeter--- set proxy recording request
若依如何解决导出使用下载插件出现异常?