通知客户端上的 SignalR 服务器意外断开连接(可耻地)

Notify SignalR Server On Client Disconnected Accidentally (Disgracefully)

我正在按照 this answer 设置我的 GlobalHost 配置,以便在 客户端无法访问时监听 :

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

并且覆盖 OnDisconnected 方法在我的 HUB Class 中设置客户端已断开连接

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

我正在使用 Xamarin for android 作为客户端,并通过覆盖 [=] 调用 Stop() 方法我的 activity 的 32=]OnStop() 方法,像这样:

       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();
        }

其次,我编写了一个明确的 hubmethod 来调用何时明确通知我的服务器我的客户端已停止工作。该方法适用于 OnStop 事件。

我的实际问题是如果 以上所有内容都无法在 activity 停止 应用程序关闭 [=] 上调用 OnDisconnected 方法41=].

有什么我遗漏的东西不允许它发生吗?

更新: 我已尝试将传输级别更改为 WebSocket,但如智能感知中所述,Xamarin SDK for SignalR 中未提供它。

由于 Xamarin 不提供 WebSocketTransport,我建议使用 "Ping" 解决方法。

  1. 在服务器端实现 Ping() 方法。
  2. 定期从客户端调用此方法(比如超时间隔的 1/2)。
  3. 在此方法中保存 ConnectionIdDateTime key/value 与服务器端的静态 ConcurrentDictionary 配对。
  4. 运行 服务器端后台任务并检查 DateTime 所有字典键。
  5. 删除旧的并调用适当的代码。