您可以连接到位于不同主机/服务器上的集线器吗?

Can you connect to a hub that is located on a different host / server?

假设我在 www.website.com 上有一个网站。我的带有 signalr 的 SaaS 托管在 www.signalr.com.

我可以从 www.website.com 连接到 www.signalr.com 信号服务器吗?

而不是:

var connection = $.hubConnection();
var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');

类似于:

var connection = $.hubConnection();
var contosoChatHubProxy = connection.createHubProxy('www.signalr.com/contosoChatHub');

简短回答:是 - As the SinalR documentation exemplifies.

第一步是在您的服务器上启用跨域。现在,您可以启用来自所有域的呼叫,也可以仅启用来自指定域的呼叫。 ()

    public void Configuration(IAppBuilder app)
        {
            var policy = new CorsPolicy()
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true,
                SupportsCredentials = true
            };

            policy.Origins.Add("domain"); //be sure to include the port:
//example: "http://localhost:8081"

            app.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(policy)
                }
            });

            app.MapSignalR();
        }

下一步是配置客户端以连接到特定域。

使用生成的代理(see the documentation for more information),您将按以下方式连接到名为 TestHub 的集线器:

 var hub = $.connection.testHub;
 //here you define the client methods (at least one of them)
 $.connection.hub.start();

现在,您唯一需要做的就是指定 URL 服务器上配置 SignalR 的位置。 (基本上是服务器)。

默认情况下,如果不指定,则默认为与客户端同域

`var hub = $.connection.testHub;
 //here you specify the domain:

 $.connection.hub.url = "http://yourdomain/signalr" - with the default routing
//if you routed SignalR in other way, you enter the route you defined.

 //here you define the client methods (at least one of them)
 $.connection.hub.start();`

应该就是这样。希望这可以帮助。祝你好运!