SignalR从服务器流到客户端

时间:2020-05-12 15:37:49

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

我无法让服务器使用SignalR将数据流传输到客户端。流仅获得1值,在这种情况下为0,然后退回到javascript complete回调方法。需要一些帮助来弄清楚为什么它不起作用。这是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);

    })();

1 个答案:

答案 0 :(得分:0)

我找到了答案,使服务类单身,并在其中添加了渠道。然后我从集线器调用了单例类,这样我就获得了服务器和客户端之间通道的相同实例。