c# - 在 .Net 客户端中创建多个 Signalr hub 代理

标签 c# signalr signalr.client

我开始使用 SignalR(.Net 客户端),在我目前看到的示例中,它们创建连接,然后创建集线器代理,然后启动连接,例如:-

var hubConnection = new HubConnection("http://localhost:8080/");

var fooProxy = hubConnection.CreateHubProxy("FooHub");
var barProxy = hubConnection.CreateHubProxy("BarHub");

hubConnection.Start().Wait();

// The proxies can now be used

我的服务器将由多个集线器组成(主要为客户端提供请求-响应式操作),但客户端应该创建它可能需要的所有代理感觉不对启动,然后将它们传递给客户端中的其他类使用。

是否可以仅在需要时(例如在方法中)创建集线器代理,然后在完成时将其丢弃? (我已经试过了,但是一旦连接开始,SignalR 将不允许您创建集线器代理)。或者创建中心代理是否“昂贵”,因此为什么要“预先”完成?

如果我坚持以这种方式创建代理,那么将它们暴露给其余客户端代码的好方法是什么?某种单例工厂?

最佳答案

错误信息很清楚——连接建立后不能创建代理。在建立连接时,SignalR 需要知道您对哪些集线器感兴趣。来自 documentation :

For JavaScript clients you have to register at least one event handler before calling the Start method to establish the connection. This is not necessary for .NET clients. For JavaScript clients, the generated proxy code automatically creates proxies for all Hubs that exist on the server, and registering a handler is how you indicate which Hubs your client intends to use. But for a .NET client you create Hub proxies manually, so SignalR assumes that you will be using any Hub that you create a proxy for.

(我相信这基本上归结为他们如何在幕后设计他们的协议(protocol),并且基本上是当建立连接时,发送的第一个信息是关于正在使用的集线器,然后是连接只是用来传递实际的方法调用信息,但我绝不是专家)

Is it possible to create a hub proxy only when it's needed (e.g. in a method) then dispose of it when finished with?

除非您还想建立一个单独的 HubConnection 对象,否则不会。取决于您希望每个客户端创建多少个连接。

Or is it "expensive" to create a hub proxy, hence why it's all done "up front"?

代理并不昂贵,但启动 HubConnection 是昂贵的。在决定他们会让您在开始连接之前创建代理之后,显然您会发现的每个示例都会这样做。

If I'm stuck with creating the proxies in this way, what would be a good way of exposing them to the rest of the client code? Some kind of singleton factory?

无论您最喜欢什么 - 如果您愿意,可以将它们存储在静态类的静态字段中(最接近 C# 的全局变量)。对我来说,除了玩具项目之外的任何东西都倾向于总是有一个依赖注入(inject)组件,所以对我来说,我会尽早创建代理并将它们放入 DI 容器中。它们可以安全地作为单例存储在容器中,因为:

The proxy object is thread-safe. In fact, if you call HubConnection.CreateHubProxy multiple times with the same hubName, you get the same cached IHubProxy object.

关于c# - 在 .Net 客户端中创建多个 Signalr hub 代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21112147/

相关文章:

c# - 从 PictureBox 解锁图像

c# - 在 RichTextBox 中设置/取消设置斜体

c# - 如果Both Checkboxes flag false怎么办?

javascript - 多日持久信号器连接模式

.net - SignalR:客户端和服务器均为 "reconnect",但推送未到达客户端

c# - 在 .NET 项目中复制 native DLL 的最简洁方法

c# - 关于 sqlDependency 更改的 SignalR 重复消息

asp.net-mvc - 如何将 signalr 集成到 typescript 项目中?

c# - 客户端未收到来自 Controller 的 SignalR 消息

asp.net - SignalR 客户端返回 HTTP 错误 400 错误请求