转到此线程阅读...下面的继续...也不需要 onstatechange 事件...阅读 msdn 链接它将为you提供更多帮助
如何在 Hub 类中处理连接生命周期事件
处理连接生命周期事件的典型原因是跟踪用户是否连接,并跟踪用户名和连接 ID 之间的关联。要在客户端连接或断开连接时运行您自己的代码,请覆盖 Hub 类的 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。
当 SignalR 可以自动恢复的连接暂时中断时调用 OnReconnected 方法,例如在连接超时之前暂时断开和重新连接电缆时。 OnDisconnected 方法在客户端断开连接且 SignalR 无法自动重新连接时调用,例如当浏览器导航到新页面时。因此,给定客户端的可能事件序列是 OnConnected、OnReconnected、OnDisconnected;或 OnConnected、OnDisconnected。您不会看到给定连接的 OnConnected、OnDisconnected、OnReconnected 序列。
在某些情况下不会调用 OnDisconnected 方法,例如当服务器关闭或应用程序域被回收时。当另一台服务器上线或 App Domain 完成其回收时,一些客户端可能能够重新连接并触发 OnReconnected 事件。
有关详细信息,请参阅了解和处理 SignalR 中的连接生命周期事件。
调用者状态未填充
连接生命周期事件处理程序方法是从服务器调用的,这意味着您在客户端的状态对象中放置的任何状态都不会填充到服务器的 Caller 属性中。有关 state 对象和 Caller 属性的信息,请参阅本主题后面的如何在客户端和 Hub 类之间传递状态。
如何从 Context 属性中获取有关客户端的信息
要获取有关客户端的信息,请使用 Hub 类的 Context 属性。 Context 属性返回一个 HubCallerContext 对象,该对象提供对以下信息的访问:
调用客户端的连接ID。
string connectionID = Context.ConnectionId;
连接 ID 是 SignalR 分配的 GUID(您无法在自己的代码中指定该值)。每个连接都有一个连接 ID,如果您的应用中有多个 Hub,则所有 Hub 使用相同的连接 ID。