如何使用SignalR Hub将消息从服​​务器发送到客户端

我刚刚开始探索signalR,我希望能够从服务器向所有客户端发送消息。

这是我的中心

using System; using System.Collections.Generic; using System.Linq; using System.Web; using SignalR; using SignalR.Hubs; using SignalR.Hosting.Common; using SignalR.Hosting.AspNet; using System.Threading.Tasks; namespace MvcApplication1 { public class Chat : Hub { public void Send(String message) { // Call the addMessage methods on all clients Clients.addMessage(message); } } } 

这是我的客户页面

   $(function () { //Proxy created on the fly var chat = $.connection.chat; // Declare a function on the chat hub so the server can invoke it chat.addMessage = function (message) { $("#messages").append("
  • " + message + "
  • "); }; $("#broadcast").click(function () { // call the chat method on the server chat.send($("#msg").val()); }); $.connection.hub.start(); }); }

    这一切都很完美,我可以在两个不同的浏览器之间“聊天”。

    我要做的下一件事是从服务器向所有客户端发送消息。

    所以我尝试了这个。

      using SignalR; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System; using System.Web.Routing; using SignalR; using SignalR.Hubs; namespace MvcApplication1 { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { var aTimer = new System.Timers.Timer(1000); aTimer.Elapsed += aTimer_Elapsed; aTimer.Interval = 3000; aTimer.Enabled = true; AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { var context = GlobalHost.ConnectionManager.GetHubContext(); context.Clients.Send("Hello"); } } } 

    这似乎不起作用。 定时器工作,“aTimer_Elapsed”事件handeler每3秒运行一次,但聊天中心上的“发送”方法永远不会运行。

    有任何想法吗?

    我认为应该是

      void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { var context = GlobalHost.ConnectionManager.GetHubContext(); context.Clients.All.addMessage("Hello"); } 

    代替。 使用Send,您将调用客户端用于调用服务器的方法…

    是的,您必须将该行设置为:

     void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { var context = GlobalHost.ConnectionManager.GetHubContext(); context.Clients.All.addMessage("Hello"); } 

    然而,这只是一半,仍然无法正常工作。

    在你的Js中你需要写:

     $(function () { //Proxy created on the fly var chat = $.connection.chat; // Declare a function on the chat hub so the server can invoke it chat.client.addMessage = function (message) { $("#messages").append("
  • " + message + "
  • "); }; $("#broadcast").click(function () { // call the chat method on the server chat.client.addMessage($("#msg").val()); }); $.connection.hub.start(); });

    我添加了chat.client这将添加服务器将调用的客户端集线器方法。