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

边栏推荐
- golang : MVC之models
- 在进行自动化测试,遇到验证码的问题,怎么办?
- Redis master-slave architecture lock failure problem (master-slave)
- [51nod1676 undirected graph isomorphism] undirected graph hash [easy to understand]
- 6-18漏洞利用-后门连接
- Detailed summary of C language game dual cache to solve the flash screen problem [easy to understand]
- 【饭谈】软件测试薪资层次和分段(修仙)
- YUV420 YUV420sp 图像格式「建议收藏」
- 若依如何解决导出使用下载插件出现异常?
- [MAIXPY]kpu: load error:2005, ERR_READ_FILE: read file failed问题解决
猜你喜欢

The second short contact of gamecloud 1608

Solutions to the failure of win key in ikbc keyboard
![[redis underlying parsing] string type](/img/a6/47083b033125195ebaf80090919fe2.png)
[redis underlying parsing] string type

How to implement distributed locks with redis?

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

【GO基础02】第一个程序

立创EDA——器件的创建01-电阻(二)
![[redis underlying parsing] linked list type](/img/e8/c192629dce1a958155a562d216d532.png)
[redis underlying parsing] linked list type

这次龙蜥展区玩的新花样,看看是谁的 DNA 动了?
![[go basics 02] the first procedure](/img/af/f32762a828f384bf6aa063ebf959aa.png)
[go basics 02] the first procedure
随机推荐
2年功能测试,却感觉自己什么都不会,2022我该何去何从?
【汇编语言01】基础知识
I/O案例实操
【Flink】FLink RocksDBListState 报错 You cannot add null to a ListState
[Fantan] how to design a test platform?
在进行自动化测试,遇到验证码的问题,怎么办?
ZigBee development board (nxpzigbee Development)
kubernetes之VictoriaMetrics单节点
How to use RS485 half duplex chip correctly
New maixhub deployment (v831 and k210)
Redis configuration
Summary of function test points of wechat sending circle of friends on mobile terminal
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!
2022 the latest software tests eight part essay. Whether you can offer depends on how you recite it
JSP初识
jsp九大内置对象
GPON introduction and Huawei OLT gateway registration and configuration process
[fan Tan] after the arrival of Web3.0, where should testers go? (ten predictions and suggestions)
Automatic assembly and fuse degradation of feign