从服务器向所有客户端发送signalr消息

时间:2012-07-13 14:51:34

标签: c# asp.net-mvc signalr

这与SignalR + posting a message to a Hub via an action method有关,但我的问题有点不同:

我使用的是信号器版本0.5.2,使用集线器。在旧版本中,我们鼓励您在集线器上创建方法以向所有客户端发送消息,这就是我所拥有的:

public class MyHub : Hub
{
    public void SendMessage(string message)
    {
        // Any other logic here
        Clients.messageRecieved(message);
    }

    ...
}

所以在0.5.2中,我想向所有客户端发送消息(比如从控制器的某个地方发送消息)。如何访问MyHub实例?

我看到引用的唯一方法是:

var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
hubContext.Clients.messageRecieved("hello");

哪个好,但我想在我的集线器上调用该方法。

3 个答案:

答案 0 :(得分:19)

您可以使用静态方法执行此操作:

SignalR v.04 -

public class MyHub : Hub
{
    internal static void SendMessage(string message)
    {
        var connectionManager = (IConnectionManager)AspNetHost.DependencyResolver.GetService(typeof(IConnectionManager));
        dynamic allClients = connectionManager.GetClients<MyHub>();
        allClients.messageRecieved(message);
    }

    ...
}

SignalR 0.5 +

public class MyHub : Hub
{
    internal static void SendMessage(string message)
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
        context.Clients.messageRecieved(message);
    }

    ...
}

然后您可以这样调用:

MyHub.SendMessage("The Message!");

SignalR API上的好文章:http://weblogs.asp.net/davidfowler/archive/2012/05/04/api-improvements-made-in-signalr-0-5.aspx

由Paolo Moretti提供在评论中

答案 1 :(得分:4)

我有同样的问题,在我的例子中,addNotification是客户端方法:

var hubContext = GlobalHost.ConnectionManager.GetHubContext<SignalR.NotificationsHub>();
hubContext.Clients.addNotification("Text here");

在您的客户端,您可以添加代码以在addNotification中调用您的hub方法:

var notification = $.connection.notificationHub;
notification.addNotification = function (message) {
 notification.addServerNotification(message); // Server Side method
}

$.connection.hub.start();

集线器:

 [HubName("notificationHub")]
    public class NotificationsHub : Hub
    {
        public void addServerNotification(string message)
        {
          //do your thing
        }
    }

更新: 一遍又一遍地阅读你的问题我真的没有理由这样做。 Hub方法通常是从客户端调用的,或者我误解了你,无论如何这里是一个更新。如果你想做一个服务器端的事情然后通知客户端。

  [HttpPost]
  [Authorize]
  public ActionResult Add(Item item)
  {
      MyHubMethodCopy(item);
      var hubContext = GlobalHost.ConnectionManager.GetHubContext<SignalR.NotificationsHub>();
    hubContext.Clients.addNotification("Items were added");

  }

  private void MyHubMethodCopy(Item item)
  {
      itemService.AddItem(item);
  }

答案 2 :(得分:1)

ASP.NET Core 2.x和3.x的更新:

您可以在有依赖注入的任何地方轻松访问Hub实例:

public class HomeController : Controller
{
    private readonly IHubContext<MyHub> _myHubContext;

    public HomeController(IHubContext<MyHub> myHubContext)
    {
        _myHubContext = myHubContext;
    }

    public void SendMessage(string msg)
    {
        _myHubContext.Clients.All.SendAsync("MessageFromServer", msg);
    }
}

如果它给您语法错误,请确保您具有:

using Microsoft.AspNetCore.SignalR;

并且您没有:

using Microsoft.AspNet.SignalR;
相关问题