【问题标题】:How do i receive messages periodically from Signalr to all Clients automatically ,without client input?如何在没有客户端输入的情况下自动定期从 Signalr 接收消息到所有客户端?
【发布时间】:2016-11-24 15:31:31
【问题描述】:

我是 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 创业课程:

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

    }
}

谁能为此提供解决方案?

【问题讨论】:

    标签: javascript c# signalr timedelay clients


    【解决方案1】:

    如果你像现在一样继续递归调用Send() 方法,你会得到一个stackoverflow 异常。只需将方法内的代码包装在 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 循环中。

    【讨论】:

    • 感谢您的回答。它工作正常..但在那之后,我遇到了一个异常。我该如何解决它?未捕获的类型错误:无法读取未定义的属性“客户端”
    • @G.Thirunavukkarasu 这是another question,它针对客户端上的更多 SignalR :)
    • 谢谢安德鲁。我会检查的
    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 2021-12-22
    • 2013-05-21
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多