c# - signalr 我如何从服务器向调用者发布消息

标签 c# asp.net-mvc-4 signalr

我正在使用 Signalr 1.1.4,因为我仍在使用 .net4,所以无法升级到 signalr 2。

基本上,我想从服务器向调用者发送消息,以避免消息发送到任何未启动进程的客户端。

我的集线器类看起来像这样

public class UpdateHub : Hub
{
    /// <summary>
    /// Sends the message.
    /// </summary>
    /// <param name="progressMessage">The progress message.</param>
    public void SendMessage(string progressMessage)
    {
        Clients.Client(Context.ConnectionId).sendMessage(string.Format(progressMessage));
    }
}

我的 JavaScript 看起来像这样

    // get handle to subscriptionUpload hub generated by SignalR 
    var updateHub = $.connection.UpdateHub;

    // establish the connection to the server and start server-side operation
    $.connection.hub.start();

    updateHub.client.sendMessage = function (message)
    {
        $("container").empty();
        $("container").append(message);
    }

现在在我的 Controller 操作方法中我想做这样的事情

UpdateHub hub = new UpdateHub();
hub.SendMessage("process has started");

//continue on with long process

hub.SendMessage("process has ended");

这可能吗?

最佳答案

我们可以在文档 documentation 中找到什么:

You don't instantiate the Hub class or call its methods from your own code on the server; all that is done for you by the SignalR Hubs pipeline. SignalR creates a new instance of your Hub class each time it needs to handle a Hub operation such as when a client connects, disconnects, or makes a method call to the server.

Because instances of the Hub class are transient, you can't use them to maintain state from one method call to the next. Each time the server receives a method call from a client, a new instance of your Hub class processes the message. To maintain state through multiple connections and method calls, use some other method such as a database, or a static variable on the Hub class, or a different class that does not derive from Hub. If you persist data in memory, using a method such as a static variable on the Hub class, the data will be lost when the app domain recycles.

然后:

If you want to send messages to clients from your own code that runs outside the Hub class, you can't do it by instantiating a Hub class instance, but you can do it by getting a reference to the SignalR context object for your Hub class.

您可以获取您的中心的上下文:GlobalHost.ConnectionManager.GetHubContext<YourHub>()

然后您可以使用它来调用客户端的方法,如下所示:

context.Clients.All.YourMethod(params);

context.Clients.Client(someConnectionID).YourMethod(params);

但在这种情况下,您将无法使用Context.ConnectionId在这种方法中,因为您没有直接连接到集线器。在这种情况下,您需要将连接存储在某个地方(静态变量、缓存、数据库等),然后使用它来确定应该调用哪个客户端。

希望能有所帮助。

关于c# - signalr 我如何从服务器向调用者发布消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36983203/

相关文章:

c# - SignalR 无法建立 SSL 连接

c# - 您如何模拟 IAsyncEnumerable?

c# - 与声明实例变量的方式不同

asp.net-mvc - MVC4 将模型从 View 传递到 Controller

c# - SignalR 广播消息在停止/启动后重复

c# - Signalr 无法连接远程服务器

C# 编译器错误?用于 Expression 中只写属性的对象初始值设定项语法使 csc 崩溃

c# - 在 .NET 中将 Int 数组写入 Stream

html - Kendo UI MVC4 网格列标题与数据不对齐

javascript - 为什么当我尝试在 JavaScript 中解析 JSON 时出现错误