定期使用signalr向所有客户发送消息。

问题描述 投票:3回答:5

我想在一个特定的时间间隔后,使用集线器从服务器向所有连接的客户端发送一些数据。我如何使用signalr集线器来完成这个任务。

asp.net signalr signalr-hub
5个回答
-1
投票

只要添加

Thread.Sleep(5000);

在您的发送方法中。

例如

    public void Send(string name, string message)
    {
        Thread.Sleep(5000);
        //call the broadcast message to upadate the clients.
        Clients.All.broadcastMessage(name, message); 
    }

希望能帮到你

编辑

下面的代码是每5秒显示一次当前时间。

下面是它的脚本。

<script type="text/javascript">
    $(function () {
        $.connection.hub.logging = true;
        $.connection.hub.start();
        // Declare a proxy to reference the hub.  
        var chat = $.connection.chatHub;

        //Appending the responce from the server to the discussion id
        chat.client.currentTime = function (time) {
            $('#discussion').append("<br/>" + time + "<br/>");
        };

        // Start the connection. 
        $.connection.hub.start().done(function () {

            //Call the server side method for every 5 seconds
            setInterval(function () {
                var date = new Date();
                chat.client.currentTime(date.toString());
            }, 5000);
        });

    }); 
</script>

<div id="discussion"></div>

在HubClass上写下以下内容:

public class ChatHub: Hub
   {
        public void currentTime(string date)
        {
            Clients.All.broadCastTime(date);
        }
   }

5
投票

旋转起来 System.Threading.Timer并从它的回调中使用特定的集线器广播消息。

Global.asax.Ltd.的回调,并从它的回调中使用特定的集线器广播消息。

private Timer timer;
public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapHubs("~/signalr2");
        timer = new Timer(TimerCallback(timerCallback), null, Timeout.Infinite, 1000);
    }
}

检查 "在枢纽外通过枢纽广播 "部分,在... SignalR wiki页面.


1
投票

使用 ReactiveExtensions 然后设置一个 观察者.区间 调用。然后reactive会自动调用lambda,可以广播给你的客户。


0
投票

我偶然发现了Jason Roberts的这个帖子=&gt。http:/dontcodetired.comlogpostUsing-Server-side-Timers-and-SignalR-in-ASPNET-MVC-Applications.aspx。

他使用IRegisteredObject和HostingEnvironment.RegisterObject,然后用一个 System.Threading.Timer 在做的类中,我自己还没试过,但看起来就是这种东西。

© www.soinside.com 2019 - 2024. All rights reserved.