简体   繁体   中英

Connecting to SignalR Server from Client

I have a web server acting as SignalR server today, where the connections from JS are coming in to correct Hub and are handled correctly.

Example of the Register and start JS side

hub = $.connection.webRTCHub;
$.connection.hub.qs = "type=pusher";

$.connection.hub.start().done(function () {
     connectionId = $.connection.hub.id;
     log("Connected with id ", $.connection.hub.id);
});

When trying to connect to this SignalR server with the C# SignalR Client Nuget-package, I get connected, I get a connection ID, but I do not think I get connected to correct hub because non of the logging is triggered, nor the correct responses are sent to rest of clients.

I am using the trace log for SignalR and it is showing connections, and showing that the ID is connecting. Below is the connection code from the C# client

connection = new HubConnection("http://localhost/signalr/hubs/webRTCHub");
await connection.Start();
MessageBox.Show(connection.ConnectionId);

I have also tried

connection = new HubConnection("http://localhost/signalr/webRTCHub");

and

connection = new HubConnection("http://localhost/");

Can someone point me into the right direction where to start?

I cant see it here, but you need to create a HubProxy for the Hub you want to connect to.

I assume your hub is "webRTCHub".

using(var connection = new HubConnection("http://localhost/"))
{
  var hubProxy = _connection.CreateHubProxy("webRTCHub");
  hubProxy.On("yourevent", () =>
  {
    _logger.Debug("Event recieved");
  });

  await _connection.Start();
}

Make sure you're registering your hub's route in app start, for example in case your using .NET core:

 app.UseSignalR(routes =>
 {
     routes.MapHub<webRTCHubHub>("/signalr/hubs/webRTCHub");
 });

While the class webRTCHub should look something like this:

public class webRTCHub : Hub
{
    public async Task SendNotification(string userId, string message)
    {
        await Clients.User(userId).SendAsync("ReceiveNotification", "You have a new message: " + message);
    }
    public override async Task OnConnectedAsync()
    {
        await base.OnConnectedAsync();
    }
    public override async Task OnDisconnectedAsync(Exception exception)
    {
        await base.OnDisconnectedAsync(exception);
    }
}

For the js side:

"use strict";

var connection;

connection = new signalR.HubConnectionBuilder()
    .withUrl('http://localhost/signalr/hubs/webRTCHub')
    .build();

connection.on('ReceiveNotification', (message) => {
   // show the message maybe
})

connection.start().catch(function (err) {
   return console.error(err.toString())
});

connection.on('finished',(update)=>{
   connection.stop();
});

To send back a message from the client to the server you should create a method as well in the class and call that from the script

Update: Packages and Services

for ASP.NET :

NuGet Packages:

Microsoft.AspNet.SignalR

Mapping Route in Application_Start

RouteTable.Routes.MapHubs("/signalr/hubs/webRTCHub", new webRTCHub());

for .NET Core :

Make sure to install the following package and add SignalR in ConfigureServices

Microsoft.AspNetCore.SignalR

public void ConfigureServices(IServiceCollection services)
{
   // ...
   services.AddSignalR();
   // ...
}

I guess you have not created any custom routes to handle signalr requests. You should initialize the HubConnection object without any url which will initialize the url of the connection object to "/signalr" as a default value.

connection = new HubConnection("");

or just

connection = new HubConnection();

Since you are using .NET FW and not .NET Core, you should configure the hub on the server like:

On your startup:

public void Configuration(IAppBuilder app)
{
    //Branch the pipeline here for requests that start with "/signalr"
    app.Map("/signalr", map =>
   {
       map.UseCors(CorsOptions.AllowAll);
       var hubConfiguration = new HubConfiguration { };
       map.RunSignalR(hubConfiguration);
   });
}

The package you use:

Microsoft.AspNet.SignalR;

Microsoft.Owin;

Then on client side is the same for FW and Core, just point to your hub.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM