SignalR OnConnected and OnDisconnected not firing

2020-04-03 03:04发布

问题:

I'm having trouble with OnConnected and OnDisconnected overrides in my Hub not firing.

For replication purposes, I've got a very simple Hub:

public class OnlineHub : Hub
{
    public void TestMethod()
    {
        var a = 1;
    }

    public override System.Threading.Tasks.Task OnConnected()
    {
        return Clients.All.connected(Context.ConnectionId, DateTime.Now.ToString());
    }

    public override System.Threading.Tasks.Task OnDisconnected()
    {
        return Clients.All.disconnected(Context.ConnectionId, DateTime.Now.ToString());
    }
}

And an aspx page:

<script type="text/javascript">
    $(function () {
        $("#btn").click(function () {
            $.connection.onlineHub.server.testMethod();
        });

        $.connection.onlineHub.server.connected = function (id, date) {
            $("#results").append("connected: " + id + " : " + date + "</br>");
        };

        $.connection.onlineHub.server.disconnected = function (id, date) {
            $("#results").append(("connected: " + id + " : " + date + "</br>");
        };

        $.connection.onlineHub.connection.start();
    });

</script>

I'm using jQuery 1.6.4 and signalR 1.0.0-alpha2. The client side connected and disconnected methods are not being executed. And if I put a breakpoint in OnConnected or OnDisconnected, the breakpoints don't hit.

The connection is being made as my TestMethod calls ok and I'm getting a connectionId back from signalR's negotiate call.

I'm sure I'm missing something simple.

Thanks in advance.

回答1:

Your client handlers should probably look like this:

$.connection.onlineHub.client.connected = function(){...}


回答2:

It also turns out that on a script you need to define at least one client callback for events to be raised on the hub. Be careful with this when expected OnConnected and OnDisconnected to be called.



回答3:

Figured it out. I was calling the methods on the server object rather than the client:

$.connection.onlineHub.server.connected = function (id, date) {
        $("#results").append("connected: " + id + " : " + date + "</br>");
    };

    $.connection.onlineHub.server.disconnected = function (id, date) {
        $("#results").append(("connected: " + id + " : " + date + "</br>");
    };

should be

$.connection.onlineHub.client.connected = function (id, date) {
        $("#results").append("connected: " + id + " : " + date + "</br>");
    };

    $.connection.onlineHub.client.disconnected = function (id, date) {
        $("#results").append(("connected: " + id + " : " + date + "</br>");
    };

So it looks like if signalR hasn't got anything defined for the task within the OnDisconnected or OnConnected, then they don't get fired. Which makes sense.