SignalR:客户端断开连接
本文关键字:连接 断开 客户端 SignalR | 更新日期: 2023-09-27 18:28:19
SignalR如何处理客户端断开连接?如果我陈述以下内容,我是对的吗?
- SignalR将通过Javascript事件处理检测浏览器页面关闭/刷新,并将适当的数据包发送到服务器(通过持久连接)
- SignalR不会检测到浏览器关闭/网络故障(可能只是超时)
我瞄准了长长的投票交通工具。
我知道这个问题,但我想澄清一下。
如果用户刷新页面,则视为新连接。您认为断开连接是基于超时的,这是正确的。
您可以通过实现SignalR.Hubs.IConnected
和SignalR.Hubs.IDisconnect
来处理集线器中的连接/重新连接和断开连接事件
上面提到SignalR 0.5.x
来自官方文件(目前为v1.1.3):
public class ContosoChatHub : Hub
{
public override Task OnConnected()
{
// Add your own code here.
// For example: in a chat application, record the association between
// the current connection ID and user name, and mark the user as online.
// After the code in this method completes, the client is informed that
// the connection is established; for example, in a JavaScript client,
// the start().done callback is executed.
return base.OnConnected();
}
public override Task OnDisconnected()
{
// Add your own code here.
// For example: in a chat application, mark the user as offline,
// delete the association between the current connection id and user name.
return base.OnDisconnected();
}
public override Task OnReconnected()
{
// Add your own code here.
// For example: in a chat application, you might have marked the
// user as offline after a period of inactivity; in that case
// mark the user as online again.
return base.OnReconnected();
}
}
在SignalR 1.0中,SignalR.Hubs.IConnected和SignalR.Hubs.IDisconnect不再实现,现在它只是集线器本身的覆盖:
public class Chat : Hub
{
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected()
{
return base.OnDisconnected();
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
}