一般的用于处理连接的生命周期事件是用于跟踪一个用户是否连接,或者用于保持跟踪用户名和连接ID之间的关系,处理生命周期事件可以通过重载 OnConnected, OnDisconnected, 和OnReconnected加方法入自己的代码,例子如下:
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();
}
}
何时 OnConnected, OnDisconnected, 和OnReconnected 会被调用?
浏览器跳转新页,接着需要建立一个新的连接, 意味着SignalR 将会执行OnDisconnected方法,接着执行OnConnected 方法. 当一个新的连接建立,SignalR 总是产生一个新的连接ID(connection ID).
OnReconnected 方法将会在短暂的失联后自动恢复时调用, 例如网络电缆中断短暂失联,在超期时间内重连。
OnDisconnected 方法将会调用,当客户端连接断开并且不能自动重连的时候,例如,当浏览器跳转到新页面. 因此, 一个可能的事件序列是OnConnected, OnReconnected, OnDisconnected; 或者OnConnected, OnDisconnected. 不会发生序列如下: OnConnected, OnDisconnected, OnReconnected .
OnDisconnected 方法在某些场景不会被调用,例如服务器宕机或者app域循环, 当另一个服务器上线或者app域完成了循环,一些客户端可能能够执行重连同时调用OnReconnected 事件.
更多信息, 参见Understanding and Handling Connection Lifetime Events in SignalR..