C#通过SignalR直接返回流式响应内容

1、背景

实现流式响应基本上分为两大技术方案:(1)基于HTTP的Stream处理;(2)基于socket的连接。前者的实现方式有:《C#通过API接口返回流式响应内容—SSE方式》和《C#通过API接口返回流式响应内容—分块编码方式》。后者有:《C#通过API接口返回流式响应内容—SignalR方式》。
在上一篇的SignalR文章中,本质上还是是用socket发消息的功能,但实际上SignalR本身也是支持流式处理的。本篇阐述通过SignalR直接返回流式内容。并且个人认为比较适合DeepSeek的流式响应的。

2、效果

在这里插入图片描述

3、具体代码

3.1 服务器端的代码

新创建一个StreamHub,实现Hub功能
在这里插入图片描述
具体代码如下:

using Microsoft.AspNetCore.SignalR;
using System.Threading.Channels;

namespace SignalRHub.Hubs
{
    public class StreamHub:Hub
    {
        public ChannelReader<string> DeepSeekStream(string inputStr,CancellationToken cancellationToken)
        {
            var channel = Channel.CreateUnbounded<string>();

            _ = WriteItemsAsync(channel.Writer, inputStr, cancellationToken);

            return channel.Reader;
        }
        //将返回的内容写入到流中
        private async Task WriteItemsAsync(ChannelWriter<string> writer,string inputStr,CancellationToken cancellationToken)
        {
            Exception localException = null;
            try
            {
                //模拟deepseek的对话内容
                var phrases = new string[] { "你好!", "我是", "北京清华长庚医院", "信息管理部的", "郑林" };

                foreach (var item in phrases)
                {
                    await writer.WriteAsync(item, cancellationToken);
                    await Task.Delay(1000, cancellationToken);
                }
            }
            catch (Exception ex)
            {
                localException = ex;
            }
            finally
            {
                writer.Complete(localException);
            }
        }
    }
}

3.2 前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SignalR Client</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.18/signalr.min.js"></script>
</head>
<body>
    <h3>流式响应</h3>
    <div id="stockPrices"></div>

    <script>
        const stockPricesDiv = document.getElementById("stockPrices");

        stockPricesDiv.addEventListener("click", (event) =>{

            sendMsgAndReturnStream("Hello");

        });
        const connection = new signalR.HubConnectionBuilder()
                            .withUrl("http://localhost:5071/dsstream")
                            .configureLogging(signalR.LogLevel.Information)
                            .build();
        
        async function start() {
            try {
                await connection.start().then(() => {
                    sendMsgAndReturnStream("Hello");
                });
                console.log("SignalR Connected.");
            } catch (err) {
                console.log(err);
                setTimeout(start, 5000);
            }
        };

        connection.onclose(async () => {
            await start();
        });

        // Start the connection.
        start();
  
        function sendMsgAndReturnStream(msg)
        {
            connection.stream("DeepSeekStream", msg)
                                .subscribe({
                                next: (item) => {
                                    stockPricesDiv.innerHTML+= item +'&nbsp;'; 
                                },
                                complete: () => {
                                    stockPricesDiv.innerHTML+= "已完成"; 
                                },
                                error: (err) => {
                                    stockPricesDiv.innerHTML+= "异常"+err; 
                                },
                            });
        }
    </script>
</body>
</html>

4、参考资料

1、在 ASP.NET Core SignalR 中使用流式传输

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值