SignalR从客户端向服务器发送消息错误

问题描述 投票:1回答:1

我正在尝试从c#控制台应用程序向我的ASP.NET Core Hub发送消息。

服务器正在运行,但是当我尝试向集线器发送消息时,我得到了期望值:

Exception抛出:Microsoft.AspNet.SignalR.Client.dll中的'System.InvalidOperationException'Microsoft.AspNet.SignalR.Client.dll中发生了类型为'System.InvalidOperationException'的未处理异常尚未建立连接。

我不知道为什么客户端没有连接。我也试图像这样启动连接:

connection.Start()。Wait();

但是随后将永远不会执行“客户端连接”的打印!

服务器

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            // register middleware for SignalR
            app.UseSignalR(routes =>
            {
                // the url most start with lower letter
                routes.MapHub<TestHub>("/hub");
            });

        }

HubClass

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.SignalR;

namespace CoreSignalRServer.Hubs
{
    public class TestHub : Hub
    {
        public void HelloMethod(String line)
        {
            System.Diagnostics.Debug.Write(line);
        }
}
}

客户

        static void Main(string[] args)
        {

            Console.WriteLine("Client started!");

            HubConnection connection = new HubConnection("http://localhost:44384/hub");
            IHubProxy _hub = connection.CreateHubProxy("TestHub");
            connection.Start();

            Console.WriteLine("Client connected!");

            string line = null;
            while ((line = System.Console.ReadLine()) != null)
            {
                _hub.Invoke("HelloMethod", line).Wait();
            }
}
c# asp.net-core signalr asp.net-core-2.1
1个回答
0
投票

我正在尝试从c#控制台应用程序向我的ASP.NET Core Hub发送消息。

据我所知,ASP.NET Core SignalR与ASP.NET SignalR的客户端或服务器不兼容。如果您想连接到集线器服务器(基于ASP.NET Core SignalR构建)并从控制台应用程序(.NET Framework)发送消息,则可以将以下客户端库安装到您的应用程序:

Microsoft.AspNetCore.SignalR.Client

并通过以下代码实现。

Console.WriteLine("Client started!");


HubConnection connection = new HubConnectionBuilder()
    .WithUrl("https://localhost:44384/hub/TestHub")
    .Build();

connection.StartAsync().Wait();

Console.WriteLine("Client connected!");

string line = null;
while ((line = System.Console.ReadLine()) != null)
{
    connection.InvokeAsync("HelloMethod", line);
}
© www.soinside.com 2019 - 2024. All rights reserved.