SSE(Server-Sent Events) 就是服务器主动“推消息”给浏览器的一种方式。平常网页要获取新数据,通常是浏览器去问服务器(比如每隔几秒刷新一下)。但 SSE 是反过来 —— 浏览器跟服务器说:“我准备好接收消息了”,然后只要服务器有新消息,就可以立刻推送过来,浏览器就能马上收到。就像你跟客服说:“有事你喊我”,然后客服有事就主动来找你。

是单向的:服务器 → 浏览器(不能反过来)。是持续连接:一旦连接上,就保持着,不断发消息。是基于 HTTP 的,不用 WebSocket 那么复杂。浏览器原生支持(EventSource 这个接口就能用)。

MCP 是一种协议,用来让前端和大语言模型(比如 ChatGPT)打交道。而 SSE 在 MCP 中的作用很关键 —— 用来实时把 AI 的回复一点点“流”出来。你有没有注意到用 ChatGPT 聊天时,回复是一行行“刷”出来的?基于LLM这种“流式”的特点, MCP 用 SSE 技术,服务器每生成一点内容就发一点给你,你这边就能“看着打字”,而不是等它全生成完才给你。

.NET10带来了SSE事件的支持,具体实现如下:

using System.Diagnostics;
using System.Runtime.CompilerServices;


var builder = WebApplication.CreateBuilder(args);


var app = builder.Build();


app.MapGet("/performance", static (CancellationToken cancellationToken) =>
{
    async IAsyncEnumerable<OSPerformance> GetHeartRate(
        [EnumeratorCancellation] CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {           
            yield return OSPerformance.Create();
            await Task.Delay(2000, cancellationToken);
        }
    }
    return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken), eventType: "osPerformance");
});
app.Run();
public class OSPerformance
{
    public float CPUUsage { get; set; }
    public float MemAvailable { get; set; }
    public DateTime Timestamp { get; set; }
    private OSPerformance(float cpuUsage, float memAvailable, DateTime timestamp)
    {
        CPUUsage = cpuUsage;
        MemAvailable = memAvailable;
        Timestamp = timestamp;
    }
    public static OSPerformance Create()
    {
        var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        var memCounter = new PerformanceCounter("Memory", "Available MBytes");
        cpuCounter.NextValue();
        float cpuUsage = cpuCounter.NextValue();
        float memAvailable = memCounter.NextValue();
        return new OSPerformance(cpuUsage, memAvailable, DateTime.UtcNow);
    }
}

先开始用.http测试,发现没有这个功能:

.NET10:api支持服务器发送事件(SSE)_System

换成postman,完美体现SSE:

.NET10:api支持服务器发送事件(SSE)_Server_02

如果这个时间关闭客户端,服务端会收到连接断开的异常!

阅读 1