【问题标题】:SignalR streaming from server to clientSignalR 从服务器流式传输到客户端
【发布时间】:2020-05-12 15:37:49
【问题描述】:

我无法让我的服务器使用 SignalR 将数据流式传输到客户端。流只获得 1 个值,在这种情况下为 0,然后回退到 javascript 完成回调方法。需要一些帮助来弄清楚为什么它不起作用。下面是Hub代码和JS代码:

public class ChatHub : Hub
    {
        private Channel<double> channel = Channel.CreateUnbounded<double>();

        public async IAsyncEnumerable<double> GetData(CancellationToken cancellationToken)
        {
            while (await channel.Reader.WaitToReadAsync())
            {
                while (channel.Reader.TryRead(out var item))
                {
                    yield return item;
                }
            }
        }

        public async Task PublishData(IAsyncEnumerable<double> data)
        {
            await foreach (var point in data)
            {
                await channel.Writer.WriteAsync(point);
            }
        }
    }

JS:

(async () => {

        const latestNumber = 0;
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/chatHub")
            .build();

        await connection.start();

        connection.stream("GetData")
            .subscribe({
                next: (item) => {
                    var li = document.createElement("li");
                    li.textContent = item;
                    document.getElementById("messagesList").appendChild(li);
                },
                complete: () => {
                    var li = document.createElement("li");
                    li.textContent = "Stream completed";
                    document.getElementById("messagesList").appendChild(li);
                },
                error: (err) => {
                    var li = document.createElement("li");
                    li.textContent = err;
                    document.getElementById("messagesList").appendChild(li);
                },
            });

        console.log(latestNumber);

    })();

【问题讨论】:

    标签: c# asp.net-core stream signalr


    【解决方案1】:

    我找到了答案,制作了一个服务类单例并将频道添加到其中。然后我从集线器调用了单例类,因此我在服务器和客户端之间获得了相同的通道实例。

    【讨论】:

      猜你喜欢
      • 2014-01-19
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多