在下面的代码示例中,我实现了一个SignalR Hub,它应该实现以下功能:
- 客户端可以通过调用Hub的Subscribe方法并提供一些id作为组名来监听Foo实例的更改。
- 取消订阅类似于调用Unsubscribe方法。
- Web应用程序的服务层可以通过调用OnFooChanged通知连接到适当id(组)的已订阅客户端发生了更改。
[Export]
public class FooHub : Hub
{
private static readonly Lazy<IHubContext> ctx = new Lazy<IHubContext>(
() => GlobalHost.ConnectionManager.GetHubContext<FooHub>());
#region Client Methods
public void Subscribe(int[] fooIds)
{
foreach(var fooId in fooIds)
this.Groups.Add(this.Context.ConnectionId, fooId.ToString(CultureInfo.InvariantCulture));
}
public void Unsubscribe(int[] fooIds)
{
foreach (var fooId in fooIds)
this.Groups.Remove(this.Context.ConnectionId, fooId.ToString(CultureInfo.InvariantCulture));
}
#endregion // Client Methods
#region Server Methods
/// <summary>
/// Called from service layer when an instance of foo has changed
/// </summary>
public static void OnFooChanged(int id)
{
ctx.Value.Clients.Group(id.ToString(CultureInfo.InvariantCulture)).onFooChanged();
}
#endregion // Server Methods
}