找回密码
 立即注册
首页 业界区 业界 基于 SSE、asp.net core razor 实现比分Live

基于 SSE、asp.net core razor 实现比分Live

胆饬 2025-6-3 00:39:47
前言

最近在项目中用到了 SSE (Server-Sent Events),用于服务的单向长连接数据推送。因为都是使用 C# 实现的,所以服务端使用的是 HttpListener ,而客户端更简单,只使用了 HttpClient ,连接了之后就一直读流,一旦流读取错误或超时,则尝试重连接。
有感于这种方式简单便捷,便一直一条路走到黑(中间踩了坑),对它进行不断打磨。最后,设计出了一款主打轻量级、兼顾性能、易扩展、开箱即用的纯 C# 实现的 SSE 工具包—— TinyHttpSSE.DotNet ,并已经开源。
简介

TinyHttpSSE.DotNet 在 github 有着详细的介绍,在此仅介绍 SSE。
Server-Sent Events(SSE)是一种基于 HTTP 协议的服务器推送技术,它允许服务器以流的方式向客户端实时推送数据。意味着支持SSE 的浏览器有着对应的支持——EventSource,所以实现 SSE 的 服务端都能与浏览器无缝衔接。
以下,我将基于 TinyHttpSSE.DotNet 和 asp.net core razor 实现一个比分直播的 Demo。
比赛得分Live Demo


  • 创建项目 asp.net core razor ,添加 nuget 包—— TinyHttpSSE.DotNet.Server
1.png

2.png


  • 修改 Program.cs ,设置 HttpSseServer 单例依赖注入,并添加 SseServerHostdService
Program.cs:
  1. var builder = WebApplication.CreateBuilder(args);
  2. // Add services to the container.
  3. builder.Services.AddSingleton((service) => {
  4.     var config=service.GetService<IConfiguration>();
  5.     //SseServerUrl:http://+:9111/msg/
  6.     return new HttpSseServer(config.GetValue<string>("SseServerUrl"));
  7. });
  8. builder.Services.AddHostedService<SseServerHostdService>();
  9. builder.Services.AddRazorPages();
  10. var app = builder.Build();
复制代码
SseServerHostdService.cs:
  1. public class SseServerHostdService : IHostedService
  2. {
  3.     private readonly HttpSseServer _server;
  4.     public SseServerHostdService(HttpSseServer httpSseServer) {
  5.         _server = httpSseServer;
  6.     }
  7.     public async Task StartAsync(CancellationToken cancellationToken) {
  8.         await Task.Run(() => {
  9.             bool result= _server.Start();
  10.         });
  11.     }
  12.     public async Task StopAsync(CancellationToken cancellationToken) {
  13.         await _server.Stopping();
  14.     }
  15. }
复制代码

  • 修改 Index.cshtml ,实现 EventSource,成为比分直播页面
Index.cshtml:
  1. @page
  2. @model IndexModel
  3. @{
  4.     ViewData["Title"] = "Home page";
  5. }
  6. @section Scripts{
  7.    
  8. }
  9.     <h1 >Welcome</h1>
  10.    
  11.         <p >
  12.             0
  13.             -
  14.             0
  15.         </p>
  16.    
  17.    
  18.    
复制代码
4.创建 Manage.cshtml 页面,比分输入功能:
Manage.cshtml:
  1. @page
  2. @model CompetitionLive.Pages.ManageModel
  3. @{
  4.    
  5. }
  6. <form  method="post">
  7.     <p>
  8.         <label for="number" asp-for="Score1"></label>
  9.         <input type="number" asp-for="Score1" id="score1" />
  10.     </p>
  11.     <p>
  12.         <label for="number" asp-for="Score2"></label>
  13.         <input type="number" asp-for="Score2" />
  14.     </p>
  15.     <p>
  16.         <label for="text2" asp-for="LastAction"></label>
  17.         <input type="text" asp-for="LastAction" />
  18.     </p>
  19.     <p><input type="submit" /></p>
  20. </form>
复制代码
Manage.cshtml.cs:
  1. public class ManageModel : PageModel
  2. {
  3.     private readonly HttpSseServer _httpSseServer;
  4.     public ManageModel( HttpSseServer httpSseServer) {
  5.         _httpSseServer = httpSseServer;
  6.     }
  7.     public int Score1 { get; set; } = 0;
  8.     public int Score2 { get; set; } = 0;
  9.     public string LastAction { get; set; }
  10.     public void OnGet()
  11.     {
  12.       
  13.     }
  14.     public void OnPost(int score1,int score2,string lastAction) {
  15.         Dictionary<string, object> dict = new Dictionary<string, object>();
  16.         dict["score1"] = score1;
  17.         dict["score2"] = score2;
  18.         dict["lastaction"] = lastAction+"<br />";
  19.         
  20.         _httpSseServer.StreamManagement.All.PushSseMsg(Newtonsoft.Json.JsonConvert.SerializeObject(dict));
  21.     }
  22. }
复制代码
5.启动运行
效果:
3.gif

附源码地址:TinyHttpSSE.Dotnet.Demo\CompetitionLive

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册