问题
I am writing a web application an it uses SignalR. On the server c#, I have two hubs. It really does need to be two otherwise I would just merge them and solve the problem.
The problem that I am having, is that while I am aware that SignalR client side, hubs will share a connection. The issue I am having, is that when I close the browser, or call stop on the client. Only 1 of my server side OnDisconnect(bool stopCalled) events will fire.
I somehow expected that both would fire when the client disconnects.
Am I being silly or doing something wrong perhaps? Any info will be greatly appreciated.
Louis
回答1:
I think the problem you are experiencing might be due to you not hooking up any event handlers (i.e. client hub methods) to the Hub that isn't triggering OnDisconnected. If this really is the cause, OnConnected also shouldn't be triggered on the same Hub.
The SignalR Hubs API Guide for the JavaScript client goes into some detail in one of its "notes" about why this is the case. Here's the relevant quote:
Note: Normally you register event handlers before calling the start method to establish the connection. If you want to register some event handlers after establishing the connection, you can do that, but you must register at least one of your event handler(s) before calling the start method. One reason for this is that there can be many Hubs in an application, but you wouldn't want to trigger the OnConnected event on every Hub if you are only going to use to one of them. When the connection is established, the presence of a client method on a Hub's proxy is what tells SignalR to trigger the OnConnected event. If you don't register any event handlers before calling the start method, you will be able to invoke methods on the Hub, but the Hub's OnConnected method won't be called and no client methods will be invoked from the server.
Every reference to the OnConnected method applies equally to the OnDisconnected method.
You can add an arbitrary event handler to your Hub before calling start() on the client to ensure that OnConnected and OnDisconnected get called on that Hub. It doesn't matter if the event handler will never be called. Ex:
$.connection.myHub.client.thisWillNeverBeCalled = function () { };
$.connection.hub.start()//...
As long as the first line is there, OnConnected and OnDisconnected should be called on MyHub
.
回答2:
In the end, after almost 2 days troubles shooting and browsing the web for answers. I ended up just merging the two hubs into a single hub. It might not be the most elegant solution, but it did get the job done and progress can now be made on the rest of the app.
Thanks for the advice though from everyone :)
Louis
来源:https://stackoverflow.com/questions/25637371/signalr-server-side-ondisconnect-only-called-for-1-hub