【问题标题】:Use SignalR as both a Hub and a Client in two ASP.NET Core 2.1 Razor web apps在两个 ASP.NET Core 2.1 Razor Web 应用程序中将 SignalR 用作集线器和客户端
【发布时间】:2018-06-29 11:37:36
【问题描述】:

我有 2 个 ASP.NET Core Razor Web 应用程序。每个应用程序都将使用 SignalR 与 Web 应用程序客户端和移动客户端进行通信。由于我的预期用途,我将 Web 应用程序设置为 Hub 和 Client,其中客户端使用 .NET SignalR 客户端。 2 个网络应用程序中的每一个都具有以下特性:

        static internal HubConnection Connection; // In the Startup class

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            Connection = new HubConnectionBuilder()
                 // Where the URL is for the OTHER web app
                .WithUrl("https://localhost:44386/NotificationHub")
                .Build();
        }

每个项目在 Hubs 文件夹中还有一个 NotificationHub 类,它派生自 Hub。

在每个应用程序的 Startup ConfigureServices 方法中,我将其作为最后一条语句:

services.AddSignalR();

在每个应用程序的启动配置方法中,我在调用 UseMvc 之前有以下内容:

app.UseSignalR(routes =>
{
    routes.MapHub<NotificationHub>("/NotificationHub");
});

在我拥有的每个 NotificationHub 类中:

    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }

因此,我不确定如何最初从一个客户端连接到集线器,我也不确定我是否正确使用了 URL。

【问题讨论】:

  • 您想使用 .net 客户端还是使用 js 连接?发布答案

标签: c# asp.net-core signalr asp.net-core-signalr


【解决方案1】:

对于使用js客户端:

1) 安装 signalr npm : npm install @aspnet/signalr

2) 在需要的页面中添加引用

3) 添加连接对象代码

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/NotificationHub")
    .configureLogging(signalR.LogLevel.Information)
    .build();
connection.start().catch(err => console.error(err.toString()));

4) 调用你的 require 方法

connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));

对于 .Net 客户端

1) 安装 nuget:Install-Package Microsoft.AspNetCore.SignalR.Client

2)

 HubConnection connection  = new HubConnectionBuilder()
            .WithUrl("https://localhost:44386/NotificationHub")
            .Build();     

 await connection.StartAsync();

 await connection.InvokeAsync("SendMessage", 
                    "user", "message");

您可以通过单击按钮或发送消息来开始连接

您可以在下面的链接中找到更多详细信息:

https://docs.microsoft.com/en-us/aspnet/core/signalr/introduction?view=aspnetcore-2.1

【讨论】:

  • 我应该提到,我想在两个应用程序中使用 .NET 客户端
  • 好的,但是我在哪里调用:await connection.StartAsync(); ?
  • 如果您想始终保持连接,您可以添加事件处理程序或仅在 ctor 中添加
  • 到目前为止,我设法让 Hub 和 Client 朝着一个方向工作。我尚未测试在每个 Web 应用程序中运行集线器和客户端。你出现了一个明显的问题 - 我如何确定 StartAsync 是否实际连接?
  • 很高兴在这里为您提供帮助stackoverflow.com/questions/47056690/… ...不要忘记标记是否保存了您的一天:)))
猜你喜欢
  • 1970-01-01
  • 2019-10-07
  • 2023-03-19
  • 1970-01-01
  • 2018-11-12
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多