Notify SignalR Server On Client Disconnected Accid

2019-04-14 16:26发布

I am setting my GlobalHost Configuration like this by following this answer to listen when the client is unreachable:

 GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(50);
 GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(30);
 GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(10);

And Overriding the OnDisconnected method in my HUB Class to set the client has been disconnected

 public override Task OnDisconnected(bool stopCalled) {
       /*My code for saving the information of disconnecting*/
        return base.OnDisconnected(stopCalled);      
    }

I am using Xamarin for android as a client and calling the Stop() method by overriding the OnStop() method of my activity, like this:

       protected override void OnStop()
        {

         //hubConnection.Stop(); previously I was using this but it takes too long to stop the hub connection in this way. so I wrote an explicit method and invoke it .

           Task hubconnection = serverHub.Invoke("StopConnection", new object[] { MethodToIdentifyDevice() }).ContinueWith(r =>
            {

            });


            base.OnStop();
        }

Secondly, I have written an explicit hubmethod to invoke when to notify my server explicitly that my client has stopped working. That method works at OnStop event.

My actual problem is that what if All of the stuff above is not able to call OnDisconnected method on activity stop or the application closed.

Is there anything I am missing which is not letting it to happen.

UPDATE: I have tried changing the Transport level to WebSocket but it is not provided in Xamarin SDK for SignalR as mentioned in the intellisense . enter image description here

1条回答
劫难
2楼-- · 2019-04-14 17:06

Since WebSocketTransport is not available at Xamarin, I advice to use "Ping" workaround.

  1. Implement Ping() method at server-side.
  2. Call this method from clients periodically (say 1/2 of the timeout interval).
  3. Within this method save ConnectionId : DateTime key/value pair to static ConcurrentDictionary at server-side.
  4. Run background Task at server-side and check DateTime for all dictionary keys.
  5. Remove old-ones and call appropriate code.
查看更多
登录 后发表回答