我有 2 个 ASP.NET Core Razor 网络应用程序。每个应用都将使用 SignalR 与 Web 应用客户端和移动客户端通信。由于我的预期用途,我已将 Web 应用设置为中心和客户端,其中客户端使用 .NET SignalR 客户端。这两个 Web 应用中的每一个都具有以下内容:
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();
}
每个项目在"中心"文件夹中都有一个从中心派生的通知中心类。
在每个应用程序的启动配置服务方法中,我都有最后一条语句:
services.AddSignalR();
在每个应用程序的启动配置方法中,我在调用UseMvc之前有以下内容:
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/NotificationHub");
});
在每个通知中心类中,我都有:
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
因此,我不确定最初如何从一个客户端连接到集线器,我也不确定我是否正确使用了 URL。
对于使用 js 客户端:
1( 安装信令 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( 调用您的需求方法
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://learn.microsoft.com/en-us/aspnet/core/signalr/introduction?view=aspnetcore-2.1