如何在 SignalR 中加入/离开群组?
How to join / leave a group in SignalR?
我在我的 Angular 项目中使用 SignalR
,我可以通过调用名为 JoinGroup 的 Hub
方法加入一个组。
service.ts:
private startConnection(): any {
this.connection
.start()
.done((data: any) => {
this.proxy.invoke('JoinGroup', 'demoGroup'); //join user to a group
})
}
Hub.cs:
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task LeaveGroup(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
同样在我的hub里也有Leave group的方法。但是,我不知道什么时候可以像在 JoinGroup 中那样在客户端调用此方法。当然,我知道我的集线器中有 OnConnected()
、OnReconnected()
和 OnDisconnected()
方法,我可以在连接时传递组名。但是我想知道如何以及何时离开组的用户?
何时从组中删除连接取决于您的具体情况。例如,您可能希望在用户离开页面时从组中删除连接等。
但是组成员身份不会跨不同的连接持续存在。这意味着您无需在断开 SignalR 连接时手动离开组。当您断开连接时(无论是有意还是由于错误),组中的所有成员资格都将丢失。引用 Microsoft Docs:
Group membership isn't preserved when a connection reconnects. The connection needs to rejoin the group when it's re-established.
我在我的 Angular 项目中使用 SignalR
,我可以通过调用名为 JoinGroup 的 Hub
方法加入一个组。
service.ts:
private startConnection(): any {
this.connection
.start()
.done((data: any) => {
this.proxy.invoke('JoinGroup', 'demoGroup'); //join user to a group
})
}
Hub.cs:
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task LeaveGroup(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
同样在我的hub里也有Leave group的方法。但是,我不知道什么时候可以像在 JoinGroup 中那样在客户端调用此方法。当然,我知道我的集线器中有 OnConnected()
、OnReconnected()
和 OnDisconnected()
方法,我可以在连接时传递组名。但是我想知道如何以及何时离开组的用户?
何时从组中删除连接取决于您的具体情况。例如,您可能希望在用户离开页面时从组中删除连接等。
但是组成员身份不会跨不同的连接持续存在。这意味着您无需在断开 SignalR 连接时手动离开组。当您断开连接时(无论是有意还是由于错误),组中的所有成员资格都将丢失。引用 Microsoft Docs:
Group membership isn't preserved when a connection reconnects. The connection needs to rejoin the group when it's re-established.