
2024年在線市場平臺的11大最佳支付解決方案
這里去掉“使用控制器”來構(gòu)建最小API服務。
最后點擊【創(chuàng)建】。
使用 NuGet 包管理器 UI 通過搜索“SignalR”,找到“Microsoft.AspNetCore.SignalR”安裝
當然,也可以通過NuGet 包管理器控制臺來通過命令安裝:
Install-Package Microsoft.AspNetCore.SignalR
builder.Services.AddSignalR();
using Microsoft.AspNetCore.SignalR;
namespace SignalRApi
{
public class SignalRHub : Hub
{
/// <summary>
/// 發(fā)布學生成績
/// </summary>
/// <param name="name">學生姓名</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();
}
}
}
具體業(yè)務邏輯代碼:
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}:服務已啟動");
Random rnd = new Random();
int score = rnd.Next(60, 100);
string[] students = { "段譽", "蕭峰", "虛竹", "阿朱", "阿紫", "王語嫣", "木婉清", "鐘靈", "阿碧", "慕容復", "段正淳", "鳩摩智" };
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($"服務異常:{ex.Message}");
}
}
}
}
}
builder.Services.AddHostedService<WorkerService>();
app.MapHub<SignalRHub>("/hubs/score");
啟動項目,查看效果:
SignalR服務端搭建完畢,接下來,實現(xiàn)SignalR的客戶端,用控制臺程序?qū)崿F(xiàn)。
同樣的方法安裝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($"接收消息--> 學生:{name} 成績:{score} 備注:{msg}");
});
try
{
// Start the connection
hubConnection.StartAsync().Wait();
Console.WriteLine("SignalR 已連接到服務器");
}
catch (Exception ex)
{
Console.WriteLine($"SignalR 連接服務異常:{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)載微信公眾號@武穆逸仙