Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I have a website on www.website.com. My SaaS with signalr is hosted on www.signalr.com.

Can I connect to www.signalr.com signalr server from www.website.com ?

Instead of :

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

Something like :

var connection = $.hubConnection();
var contosoChatHubProxy = connection.createHubProxy('www.signalr.com/contosoChatHub');
like image 350
Evaldas Raisutis Avatar asked Sep 11 '15 08:09

Evaldas Raisutis


1 Answers

Short answer: Yes - As the SinalR documentation exemplifies.

The first step is enabling cross domain on your server. Now, you can either enable calls from all domains, or only from specified ones. (See this SO post on this matter)

    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();
        }

The next step is configuring the client to connect to a specific domain.

Using the generated proxy(see the documentation for more information), you would connect to a hub named TestHub in the following way:

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

Now, the only thing you have to do is specify the URL where SignalR is configured on the server. (basically the server).

By default, if you don't specify it, it is assumed that it is the same domain as the client.

`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();`

And that should be it. Hope this helps. Best of luck!

like image 97
radu-matei Avatar answered Sep 23 '22 06:09

radu-matei