我如何在没有客户端输入的情况下自动从 Signalr 定期接收消息到所有客户端?

How do i receive messages periodically from Signalr to all Clients automatically ,without client input?

我是 SignalR 的新手。我需要在没有客户端输入的情况下自动将消息从 SignalR 发送到所有连接的客户端,但有一些延迟?

上面的过程还要重复,同时递归?

可能吗?

在没有客户端输入的情况下,SignalR 可以自动向客户端重复发送消息吗?

这是我的 JavaScript 客户代码:

$(function () {
    var chat = $.connection.timehub;
    $.connection.hub.start();
    chat.client.broadcastMessage = function (current) {
        var now = current;
        console.log(current);
        $('div.container').append('<p><strong>' + now + '</strong></p>');
    }
};

这是我的 Timehub

public class timehub : Hub
{
    public void Send(string current)
    {
        current = DateTime.Now.ToString("HH:mm:ss:tt");
        Clients.All.broadcastMessage(current);

        System.Threading.Thread.Sleep(5000);
        Send(current);
    }
}

这是我的 Owin Startup Class:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR();

    }
}

谁能为我提供解决方案?

如果您像现在一样继续递归调用 Send() 方法,您将遇到 Whosebug 异常。只需将代码包装在 while(true) 循环中的方法中:

public class timehub : Hub
{
    public void Send()
    {
        while(true)
        {
            var current = DateTime.Now.ToString("HH:mm:ss:tt");
            Clients.All.broadcastMessage(current);
            System.Threading.Thread.Sleep(5000);
        }
    }
}

我建议将 Send() 方法移动到另一个线程,因为当前线程将永远卡在这个 while 循环中。