简体   繁体   中英

How to broadcast real-time data in SignalR?

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

    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:

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM