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

边栏推荐
- [test development methodology] experience of test development platform PK - choice
- JSP初识
- Collation of SQL statement exercises
- 若依如何解决导出使用下载插件出现异常?
- JMeter websocket接口测试
- [MAIXPY]kpu: load error:2005, ERR_READ_FILE: read file failed问题解决
- 3. Editors (vim)
- [assembly language 01] basic knowledge
- Composition of dog food
- After three years of software testing at Tencent, I was ruthlessly dismissed in July, trying to wake up my brother who was paddling
猜你喜欢
![[MAIXPY]kpu: load error:2005, ERR_ READ_ File: read file failed problem solving](/img/0b/da67b5a361a2cdfaf81568d34cf5f7.png)
[MAIXPY]kpu: load error:2005, ERR_ READ_ File: read file failed problem solving

3. Editors (vim)

突破性思维在测试工作中的应用
![[assembly language 01] basic knowledge](/img/df/d586288b8f41211141bc4e2bca20cf.png)
[assembly language 01] basic knowledge

How to implement distributed locks with redis?

Bitcoin.com:USDD代表了真正去中心化稳定币

jenkins+SVN配置

『SignalR』.NET使用 SignalR 进行实时通信初体验

Redis基础2(笔记)

2年功能测试,却感觉自己什么都不会,2022我该何去何从?
随机推荐
dovecot 设置邮箱quota
YUV420 YUV420sp 图像格式「建议收藏」
Wet- a good choice for people with English difficulties - console translation
After three years of software testing at Tencent, I was ruthlessly dismissed in July, trying to wake up my brother who was paddling
卸载npm和安装npm_使用`npm uninstall`卸载npm软件包「建议收藏」
golang : MVC之models
2022 love analysis ― bank digitalization practice report
Composition of dog food
6-18漏洞利用-后门连接
Three ways to allocate disk space
JMeter websocket interface test
C语言:随机生成数+冒泡排序
Redis基础2(笔记)
Animation curves are used every day. Can you make one by yourself? After reading this article, you will!
Unity performance optimization direction
【饭谈】细说:下克上,向上管理,向上画饼。
Redis内存淘汰机制?
How to use RS485 half duplex chip correctly
【测开方法论】测开平台pk心得-抉择
The reisson distributed lock renewal failed due to network reasons, resulting in the automatic release of the lock when the business is still executing but the lock is not renewed.