【问题标题】:Invoke a SignalR hub from .net code as well as JavaScript从 .net 代码和 JavaScript 调用 SignalR 集线器
【发布时间】:2013-02-10 03:42:32
【问题描述】:

我有一个 SignalR 集线器,我成功地从 JQuery 调用它。

public class UpdateNotification : Hub
{
    public void SendUpdate(DateTime timeStamp, string user, string entity, string message)
    {
        Clients.All.UpdateClients(timeStamp.ToString("yyyy-MM-dd HH:mm:ss"), user, entity, message);       
    }
}

像这样从 JS 成功发送更新消息

var updateNotification = $.connection.updateNotification;
$.connection.hub.start({ transport: ['webSockets', 'serverSentEvents', 'longPolling'] }).done(function () { });
updateNotification.server.sendUpdate(timeStamp, user, entity, message);

并像这样成功接收

updateNotification.client.UpdateClients = function (timeStamp, user, entity, message) {

我不知道如何从我的控制器中调用 sendUpdate。

【问题讨论】:

    标签: c# jquery asp.net-mvc signalr


    【解决方案1】:

    从您的控制器,在与集线器相同的应用程序中(而不是从其他地方,作为 .NET 客户端),您可以像这样进行集线器调用:

    var hubContext = GlobalHost.ConnectionManager.GetHubContext<UpdateNotification>();
    hubContext.Clients.All.yourclientfunction(yourargs);
    

    参见https://github.com/SignalR/SignalR/wiki/Hubs 脚下附近的从集线器外部通过集线器进行广播

    调用您的自定义方法有点不同。最好创建一个静态方法,然后您可以使用它来调用 hubContext,就像 OP 在这里一样:Server to client messages not going through with SignalR in ASP.NET MVC 4

    【讨论】:

      【解决方案2】:

      这是 SignalR quickstart 的一个示例 您需要创建一个集线器代理

      public class Program
      {
          public static void Main(string[] args)
          {
              // Connect to the service
              var hubConnection = new HubConnection("http://localhost/mysite");
      
              // Create a proxy to the chat service
              var chat = hubConnection.CreateHubProxy("chat");
      
              // Print the message when it comes in
              chat.On("addMessage", message => Console.WriteLine(message));
      
              // Start the connection
              hubConnection.Start().Wait();
      
              string line = null;
              while((line = Console.ReadLine()) != null)
              {
                  // Send a message to the server
                  chat.Invoke("Send", line).Wait();
              }
          }
      }
      

      【讨论】:

        最近更新 更多