[英]SignalR - Server side method to detect if a client disconnects from a hub?
I'm wanting to stop a System.Timers.Timer
that is running in a SignalR hub after a client closes a window/tab containing the active connection. 我想在客户端关闭包含活动连接的窗口/选项卡后停止在SignalR集线器中运行的
System.Timers.Timer
。
I have tried sending a bool value to the server by calling server code to notify the server the client is still connected or not, but it's not currently working. 我已经尝试通过调用服务器代码向服务器发送bool值来通知服务器客户端是否仍然连接,但它当前不工作。
window.onbeforeunload = function () {
profile.server.setIsConnected(false);
};
Server Side: 服务器端:
public ProfileHub()
{
timer = new Timer(15000);
timer.Elapsed += (sender, e) => { timer_Elapsed(sender, e, _isActive); };
timer.AutoReset = false;
}
[Authorize]
private void timer_Elapsed(object sender, ElapsedEventArgs e, bool active)
{
timer.Stop();
if (active)
{
System.Diagnostics.Debug.WriteLine("Timer Started");
timer.Start();
}
else
{
System.Diagnostics.Debug.WriteLine("Timer Stopped");
return;
}
// process code
}
[Authorize]
public void SetIsActive(bool isActive)
{
_isActive = isActive;
}
Is this possible and am I on the right track? 这是可能的,我是否走在正确的轨道上? I suspect it has something to do with the anonymous delegate for
timer.Elapsed
, but I'm not entirely sure. 我怀疑它与
timer.Elapsed
的匿名委托有关,但我不完全确定。
SignalR has OnConnected, OnDisconnected, and OnReconnected that are called every time the client does one of those actions. SignalR具有OnConnected,OnDisconnected和OnReconnected,每次客户端执行其中一个操作时都会调用它们。 You can simply override them:
你可以简单地覆盖它们:
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected()
{
//custom logic here
return base.OnDisconnected();
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
I've found them to be extremely useful also for debugging purposes. 我发现它们对于调试目的也非常有用。 If you're wanting to set a timer for each person, you should use some sort of connectionMapping along with the above functions to keep track of your users.
如果您想为每个人设置计时器,您应该使用某种connectionMapping以及上述功能来跟踪您的用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.