简体   繁体   English

从客户端连接到 SignalR 服务器

[英]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.我今天有一个 web 服务器充当 SignalR 服务器,其中来自 JS 的连接进入正确的集线器并得到正确处理。

Example of the Register and start JS side注册并启动 JS 端的示例

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.当尝试使用 C# SignalR 客户端 Nuget 包连接到此 SignalR 服务器时,我得到连接,也没有得到正确的连接 ID,因为没有触发集线器,但我认为我没有连接到正确的连接 ID发送到客户端的 rest。

I am using the trace log for SignalR and it is showing connections, and showing that the ID is connecting.我正在使用 SignalR 的跟踪日志,它显示连接,并显示 ID 正在连接。 Below is the connection code from the C# client下面是来自 C# 客户端的连接代码

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.我在这里看不到,但是您需要为要连接的 Hub 创建一个 HubProxy。

I assume your hub is "webRTCHub".我假设您的集线器是“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:确保您在应用程序启动中注册集线器的路线,例如,如果您使用 .NET 核心:

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

While the class webRTCHub should look something like this:虽然 class webRTCHub应该看起来像这样:

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:对于js端:

"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要将消息从客户端发送回服务器,您还应该在 class 中创建一个方法并从脚本中调用它

Update: Packages and Services更新:包和服务

for ASP.NET :对于ASP.NET

NuGet Packages: NuGet 封装:

Microsoft.AspNet.SignalR Microsoft.AspNet.SignalR

Mapping Route in Application_Start Application_Start中的映射路由

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

for .NET Core :对于.NET 核心

Make sure to install the following package and add SignalR in ConfigureServices确保安装以下 package 并在ConfigureServices中添加 SignalR

Microsoft.AspNetCore.SignalR Microsoft.AspNetCore.SignalR

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

I guess you have not created any custom routes to handle signalr requests.我猜您还没有创建任何自定义路由来处理 signalr 请求。 You should initialize the HubConnection object without any url which will initialize the url of the connection object to "/signalr" as a default value. 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:由于您使用的是 .NET FW 而不是 .NET Core,因此您应该在服务器上配置集线器,如下所示:

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:您使用的 package:

Microsoft.AspNet.SignalR; Microsoft.AspNet.SignalR;

Microsoft.Owin;微软.Owin;

Then on client side is the same for FW and Core, just point to your hub.然后在客户端对于 FW 和 Core 是相同的,只需指向您的集线器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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