gpt4 book ai didi

signalr - 连接到多个集线器并仅与一个集线器断开连接

转载 作者:行者123 更新时间:2023-12-02 13:03:32 34 4
gpt4 key购买 nike

我正在使用 Durandal 编写一个单页应用程序,并计划使用 SignalR 来实现某些功能。首先,我有一个顶部栏,用于监听服务器可能发送的通知。该站点启动与“TopBarNotificationHub”的连接。

在其中一个页面上,我想连接到另一个中心,因为两个用户可能会同时编辑此页面上的数据,并且我想通知是否有人更新了数据。没问题,这工作正常。

但是,当离开该页面时,我只想断开与第二个集线器的连接,但我找不到实现此目的的方法。如果我只是说 hub.connection.stop();与 eTopBarNotificationHub 的连接也会停止(因为它是共享的)。

有没有一种方法可以只留下一个集线器代理并让另一个集线器存在?

由于这是一个 SPA,“shell”永远不会重新加载,因此它不会再次连接到集线器...我也许可以在每次另一个页面与集线器断开连接时强制它重新连接,但可能会有一个更清洁的解决方案...

提前致谢。

//J

最佳答案

如果您在单个页面上使用多个中心,那没问题,但它们共享相同的连接,因此除了接收更新之外,它不会占用客户端上的更多资源。

因此,要“连接到集线器或从集线器断开连接”,您需要稍微重新架构。如果您在服务器端使用组而不是客户端,则可以通过调用(例如)Hub1.Register 方法并将客户端粘贴到该方法中的相关组中,从而向集线器“注册”。要“取消注册”,您可以调用(例如)Hub1.DeRegister 并从该方法中的组中删除客户端的 ConnectionId。然后,当您向客户端推送更新时,您可以只使用 Group 而不是 Clients.All

(假定服务器语言为 C#,因为您未在标记中指定)

  • 要将客户端添加到中心组:Groups.Add(Context.ConnectionId, groupNameForHub);
  • 要从中心组中删除客户端:Groups.Remove(Context.ConnectionId, id.ToString());
  • 要向该 Hub 的客户端广播:Clients.Group(groupNameForHub).clientMethodName(param1, param2);

不过,为了避免混淆,请注意 Hub1 中名为“myGroup”的组与 Hub2 中名为“myGroup”的组是分开的。

这正是推荐的方法 in the documents (复制到这里以防它们在以后的版本中移动/更改):

Multiple Hubs

You can define multiple Hub classes in an application. When you do that, the connection is shared but groups are separate:

• All clients will use the same URL to establish a SignalR connection with your service ("/signalr" or your custom URL if you specified one), and that connection is used for all Hubs defined by the service.

There is no performance difference for multiple Hubs compared to defining all Hub functionality in a single class.

• All Hubs get the same HTTP request information.

Since all Hubs share the same connection, the only HTTP request information that the server gets is what comes in the original HTTP request that establishes the SignalR connection. If you use the connection request to pass information from the client to the server by specifying a query string, you can't provide different query strings to different Hubs. All Hubs will receive the same information.

• The generated JavaScript proxies file will contain proxies for all Hubs in one file.

For information about JavaScript proxies, see SignalR Hubs API Guide - JavaScript Client - The generated proxy and what it does for you.

• Groups are defined within Hubs.

In SignalR you can define named groups to broadcast to subsets of connected clients. Groups are maintained separately for each Hub. For example, a group named "Administrators" would include one set of clients for your ContosoChatHub class, and the same group name would refer to a different set of clients for your StockTickerHub class.

关于signalr - 连接到多个集线器并仅与一个集线器断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16737678/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com