SignalR 2.2客户端没有收到任何消息

时间:2016-04-30 13:22:37

标签: javascript c# signalr

我有一个在控制台应用程序环境中运行的自托管SignalR应用程序。我通过使用包装类连接到其中的集线器,以防止我必须从我的ASP.NET项目引用SignalR.Core程序集。所以它是我的应用程序中的另一个C#类,它负责向连接的客户端广播消息。

我可以直接从Javascript调用PlanHub方法(RegisterUnregister),这些断点会受到影响。但是,当我从Hub外部的类调用客户端方法时(即使我使用Clients.All来消除组注册的问题),客户端永远不会收到消息。我做错了什么?

运行此代码时,我可以验证Clients.All.updateStatus(planId, message);代码是否成功命中,但客户端上没有任何内容记录到控制台。

以下是相关代码:

PlanHub.cs

public class PlanHub : Hub
{
    private const string GroupPrefix = "PlanGroup_";

    public void Register(int companyId)
    {
        Groups.Add(Context.ConnectionId, $"{GroupPrefix}{companyId}");
    }

    public void Unregister(int companyId)
    {
        Groups.Remove(Context.ConnectionId, $"{GroupPrefix}{companyId}");
    }
}

PlanPublisher.cs

public class PlanPublisher
{
    private readonly static Lazy<PlanPublisher> _instance = new Lazy<PlanPublisher>(() => 
        new PlanPublisher(GlobalHost.ConnectionManager.GetHubContext<PlanHub>().Clients));
    private IHubConnectionContext<dynamic> Clients { get; set; }

    private PlanPublisher(IHubConnectionContext<dynamic> clients)
    {
        Clients = clients;
    }

    public static PlanPublisher Instance => _instance.Value;

    public void UpdateStatus(int planId, string message)
    {
        //This code gets hit and no exceptions are thrown, but the clients
        //never receive the message. Using Clients.All instead of my 
        //Groups for testing -- still doesn't work
        Clients.All.updateStatus(planId, message);
    }
}

调用代码(来自另一个C#类)

PlanPublisher.Instance.UpdateStatus(plan.Id, $"Publishing started for {plan.Name}...");

的Javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> 
<script src="~/scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:8080/signalr/hubs"></script>
<script>
    $(document).ready(function() {
        $.connection.hub.url = "http://localhost:8080/signalr";

        var planMessagePublisher = $.connection.planHub;

        planMessagePublisher.client.updateStatus = function (planId, message) {
            console.log('Status: ' + planId + ' - ' + message);
        };

        $.connection.hub.start().done(function() {
            //This works! My PlanHub.Register method gets called successfully
            planMessagePublisher.server.register(@Model.CompanyId);

            // New connection ID is successfully sent to console
            console.log('Now connected, connection ID=' + $.connection.hub.id);
        });
    });
</script>

JS控制台调试器输出

jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Auto detected cross domain url.
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Client subscribed to hub 'planhub'.
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Negotiating with 'http://localhost:8080/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22planhub%22%7D%5D'.
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: webSockets transport starting.
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Connecting to websocket endpoint 'ws://localhost:8080/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAA5D8YUVyzBEG4tTlTaGn0MgAAAAACAAAAAAADZgAAwAAAABAAAABDjF1MaCTzZI0XTM8gC29xAAAAAASAAACgAAAAEAAAAKrk0jv%2FKF4YFzDvNwmSR8IoAAAAacm1d1r7dJpjOtVtCFIFRpugkubyZm1e5Z8OtOFtnhZyEBO1SO4lqhQAAABiG7hBydTiypPh8k2ZYz20ropNxw%3D%3D&connectionData=%5B%7B%22name%22%3A%22planhub%22%7D%5D&tid=6'.
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Websocket opened.
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: webSockets transport connected. Initiating start request.
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: The start request succeeded. Transitioning to the connected state.
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Now monitoring keep alive with a warning timeout of 13333.333333333332, keep alive timeout of 20000 and disconnecting timeout of 30000
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Invoking planhub.Register
jquery.signalR-2.2.0.min.js?v=8588299:8 [06:23:19 GMT-0700 (Pacific Daylight Time)] SignalR: Invoked planhub.Register

它成功注册,但从未接收任何数据。 Clients.All.updateStatus(planId, message);断点被多次命中,但控制台从未收到任何其他记录数据。

编辑:建议我查看自定义依赖项解析程序是否正在运行。除了你在这里看到的内容之外,这里发布的代码生活在自己的项目中。调用PlanPublisher.UpdateStatus() DOES的代码有一个自定义依赖项解析器,但这并不重要,因为它在自己的程序集中被隔离。 PlanPublisher.csPlanHub.cs包含在一个非常简单的项目中,该项目只引用了SignalR.Core和SignalR.SelfHost。

2 个答案:

答案 0 :(得分:3)

我试图简化你的例子(使用SignalR 2.2.0)

Hub类:

public class PlanHub : Hub
{
    private const string GroupPrefix = "PlanGroup_";

    // hubcontext
    private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <PlanHub> ();

    public void Register(int companyId)
    {
        Groups.Add(Context.ConnectionId, $"{GroupPrefix}{companyId}");
    }

    public void Unregister(int companyId)
    {
        Groups.Remove(Context.ConnectionId, $"{GroupPrefix}{companyId}");
    }

    // static method using hub context
    public static void Static_UpdateStatus(int planId, string message)
    {
        hubContext.Clients.All.updateStatus(planId, message);
    }
}

由于我实际上没有后端而且我不知道你将如何做到这一点,我只是设置一个计时器来每隔10秒从C#调用该方法。

呼叫和虚拟计时器:

    public void startTimer()
    {
        timer = new System.Timers.Timer();
        timer.Elapsed += new System.Timers.ElapsedEventHandler(ExecuteTimerJob);
        timer.Interval = 10000; // 10 sec
        timer.Start();
    }

    public static void ExecuteTimerJob(object source, System.Timers.ElapsedEventArgs e)
    {
        // this is the call from C#
        PlanHub.Static_UpdateStatus(123, "some message");
    }

JS:

$(function () {
    var planHub = $.connection.planHub;
    $.connection.hub.start().done(function () {
         console.debug('Connected to PlanHub...');
    })
    planHub.client.updateStatus = function (planId, message) {
        console.log("planId: " + planId);
        console.log("message: " + message);
    } 
});

浏览器控制台中的结果:

enter image description here

答案 1 :(得分:2)

试试这个:

public void UpdateStatus(int planId, string message)
{
    var clients = GlobalHost.ConnectionManager.GetHubContext<PlanHub>().Clients;
    clients.All.updateStatus(planId, message);
}

我认为问题是 PlanPublisher 在创建集线器上下文(以及客户端)之前已初始化。