如何在SignalR中广播实时数据?

时间:2021-09-17 03:55:14

I have a timer in Global.asax, which calls a method to send current time to all clients through SignalR every 5 seconds:

我在Global.asax中有一个定时器,它调用一个方法,每隔5秒通过SignalR向所有客户端发送当前时间:

    protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapHubs();
        var timer = new System.Timers.Timer();
        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        timer.Interval = 5000;
        timer.Enabled = true;
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        var context = GlobalHost.ConnectionManager.GetHubContext<EventHub>();
        context.Clients.All.Send(DateTime.Now.ToLongTimeString());
    }

my Hub class:

我的Hub类:

public class EventHub: Hub
{
    public void Send(string message)
    {
        Clients.All.broadcastMessage( message);
    }
}

Javascript:

$(function () {

    var context = $.connection.eventHub;
    context.client.broadcastMessage = function (message) {

    alert("clock: " + message);
    };
    $.connection.hub.start();
});

no error, but no thing occurs on running application. what's my wrong?

没有错误,但运行应用程序时没有发生任何事情。我错了什么?

1 个解决方案

#1


5  

context.Clients.All.Send(DateTime.Now.ToLongTimeString());

This will fire a method Send on the clients, it will not call

这将触发客户端上的方法Send,它不会调用

public void Send(string message)
{
    Clients.All.broadcastMessage( message);
}

#1


5  

context.Clients.All.Send(DateTime.Now.ToLongTimeString());

This will fire a method Send on the clients, it will not call

这将触发客户端上的方法Send,它不会调用

public void Send(string message)
{
    Clients.All.broadcastMessage( message);
}