這里去掉“使用控制器”來構(gòu)建最小API服務(wù)。

最后點擊【創(chuàng)建】。

2、在項目中安裝 SignalR 包

使用 NuGet 包管理器 UI 通過搜索“SignalR”,找到“Microsoft.AspNetCore.SignalR”安裝

當然,也可以通過NuGet 包管理器控制臺來通過命令安裝:

Install-Package Microsoft.AspNetCore.SignalR

3、在啟動文件Program.cs中添加?SignalR 服務(wù)

builder.Services.AddSignalR();

4、創(chuàng)建Hub類?SignalRHub.cs

using Microsoft.AspNetCore.SignalR;

namespace SignalRApi
{
public class SignalRHub : Hub
{
/// <summary>
/// 發(fā)布學(xué)生成績
/// </summary>
/// <param name="name">學(xué)生姓名</param>
/// <param name="score">得分</param>
/// <param name="msg">備注</param>
/// <returns></returns>
public async Task SendMessage(string name, int score, string msg)
{
await Clients.All.SendAsync("ReceiveScore", name, score, msg);
}
public override async Task OnConnectedAsync()
{
string connectionId = Context.ConnectionId;
await base.OnConnectedAsync();
}
}
}

5、創(chuàng)建后臺服務(wù)持續(xù)推送消息類 WorkerService.cs 

具體業(yè)務(wù)邏輯代碼:

using Microsoft.AspNetCore.SignalR;

namespace SignalRApi
{
public class WorkerService : BackgroundService
{
private readonly IHubContext<SignalRHub> _signalRHub;

public WorkerService(IHubContext<SignalRHub> signalRHub)
{
_signalRHub = signalRHub;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
Console.WriteLine($"{DateTime.Now}:服務(wù)已啟動");
Random rnd = new Random();
int score = rnd.Next(60, 100);
string[] students = { "段譽", "蕭峰", "虛竹", "阿朱", "阿紫", "王語嫣", "木婉清", "鐘靈", "阿碧", "慕容復(fù)", "段正淳", "鳩摩智" };
var name = students[rnd.Next(0, students.Length)];
await _signalRHub.Clients.All.SendAsync("ReceiveScore", name, score, $"{name}的成績是{score}");
Console.WriteLine($"{DateTime.Now}:發(fā)布成績:{name}獲取{score}分");
await Task.Delay(4000, stoppingToken);
}
catch (Exception ex)
{
Console.WriteLine($"服務(wù)異常:{ex.Message}");
}
}
}
}
}

6、最后,需要在Program.cs中映射 SignalRHub 以及添加后臺服務(wù)

builder.Services.AddHostedService<WorkerService>();

app.MapHub<SignalRHub>("/hubs/score");

啟動項目,查看效果:

SignalR服務(wù)端搭建完畢,接下來,實現(xiàn)SignalR的客戶端,用控制臺程序?qū)崿F(xiàn)。

創(chuàng)建 SignalR 客戶端

1、創(chuàng)建控制臺應(yīng)用程序

同樣的方法安裝SignalR客戶端包【Microsoft.AspNetCore.SignalR.Client】,

在Program.cs中添加代碼:

using Microsoft.AspNetCore.SignalR.Client;
//here is SignalR Sender URL
string hubUrl = "http://localhost:5000/hubs/score";
var hubConnection = new HubConnectionBuilder().WithUrl(hubUrl).Build();

// Register a handler for messages from the SignalR hub
// "ReceiveStockPrice" is the topic to which SignalR sending the singnals
hubConnection.On<string, int, string>("ReceiveScore", (name, score, msg) =>
{
Console.WriteLine($"接收消息--> 學(xué)生:{name} 成績:{score} 備注:{msg}");
});

try
{
// Start the connection
hubConnection.StartAsync().Wait();
Console.WriteLine("SignalR 已連接到服務(wù)器");
}
catch (Exception ex)
{
Console.WriteLine($"SignalR 連接服務(wù)異常:{ex.Message}");
throw;
}
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
Console.CancelKeyPress += (sender, a) =>
{
a.Cancel = true;
Console.WriteLine("SignalR 停止連接");
cancellationTokenSource.Cancel();
};
try
{
await Task.Delay(Timeout.Infinite, cancellationToken);
}
catch (TaskCanceledException)
{
}
await hubConnection.StopAsync();

Console.WriteLine("SignalR 連接已關(guān)閉");

啟動項目,查看效果:

本文章轉(zhuǎn)載微信公眾號@武穆逸仙

上一篇:

.NET REST API 中的序列化和反序列化

下一篇:

用ASP.NET Core 2.1 建立規(guī)范的 REST API -- 緩存和并發(fā)
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費