我在 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());
}
我的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();
});
没有错误,但在运行应用程序时没有发生任何事情。我错了什么?
答案 0 :(得分:5)
context.Clients.All.Send(DateTime.Now.ToLongTimeString());
这将在客户端上触发方法Send
,它不会调用
public void Send(string message)
{
Clients.All.broadcastMessage( message);
}