Server to client messages not going through with S

2019-01-25 20:48发布

I created a simple test app to reproduce a problem I'm having in my main app.

I have the following hub class:

[HubName("testHub")]
public class TestHub : Hub
{
    public TestHub()
    {
        System.Diagnostics.Debug.WriteLine("TestHub instantiated");
    }

    public void RunMe()
    {
        System.Diagnostics.Debug.WriteLine("Client Started");
    }

    public static void Notify(string msg)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
        hubContext.Clients.All.notify("Hello!");
    }
}

My test web page is:

<form action="javascript: void(0)" method="post">
    <input type="button" value="Do It!" onclick="hitHub()"/>
</form>

<div id="error"></div>
<script type="text/javascript">
    var tHub;    
    $(document).ready(function () {
        tHub = $.connection.testHub;
        tHub.notify = function (msg) {
            alert(msg);
        }
        $.connection.hub.start().done(function () {
            tHub.server.runMe();
        });
    });

    function hitHub() {
        $.ajax({
            type: "POST",
            url: "@Url.Content("~/Hub/Test")" ,
            success: function (data, textStatus, jqXHR) {
            },
            error: function (data, textStatus, jqXHR) {
                $("#error")[0].innerHTML = data.responseText;
                alert("Error notifying hub.");
            }
        });

    }
</script>

And finally, my HubController:

public class HubController : Controller
{
    [AcceptVerbs(HttpVerbs.Post)]
    public void Test()
    {
        TestHub.Notify("Got it!");
    }
}

In my Application_Start, I call RouteTable.Routes.MapHubs();

The hub gets instantiated. Then the call to runMe() gets passed to the server. This all works fine.

Where it fails is when I click on the "Do It!" button. hitHub() gets called and my HubController.Test() method gets called. TestHub.Notify("Got it!") gets executed without any errors, however nothing happens on the client.

What did I miss?

Update 1: Based on answer from JcFx, changed the javascript above so that tHub.notify is set before calling $.connection.hub.start(). The problem remains, however.

Update 2: What fiddler sees: What the Fiddler sees

Update 3: When I trace into the MessageBus.Publish() call, I notice tha the Topic has no subscriptions, so the topic never gets scheduled. I'm not sure how at what point I should be checking for the subscriptiont to be made...

1条回答
唯我独甜
2楼-- · 2019-01-25 21:18

You're using the wrong syntax:

var tHub;    
$(document).ready(function () {
    tHub = $.connection.testHub;
    tHub.client.notify = function (msg) {
        alert(msg);
    }
    $.connection.hub.start().done(function () {
        tHub.server.runMe();
    });
});

Notice the .client property on the hub to register the callback.

查看更多
登录 后发表回答