本文介绍了调用 SignalR Hub 不适用于 Asp.Net Core Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 SignalR 的新手.我正在尝试设置一个 Asp.Net Core WebAPI,以便其他客户端可以使用 SignalR 连接到它并获取实时数据.我的 Hub 类是:

I'm a newb to SignalR. I'm trying to set up a Asp.Net Core WebAPI so that other clients can connect to it using SignalR and get real-time data.My Hub class is:

public class TimeHub : Hub
{
    public async Task UpdateTime(string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", message);
    }
}

我有一个中继类如下:

public class TimeRelay : ITimeRelay
{
    private readonly IHubContext<TimeHub> _timeHubContext;

    public TimeRelay(IHubContext<TimeHub> context)
    {

        _timeHubContext = context;
        Task.Factory.StartNew(async () =>
        {
            while (true)
            {
                await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString());
                Thread.Sleep(2000);
            }
        });
    }
}

启动类:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();

    app.UseHttpsRedirection();

    app.UseSignalR((x) =>
    {
        x.MapHub<TimeHub>("/timeHub");
    });
    app.UseMvc();
}

客户端是一个控制台应用程序,代码是:

The client is a console application and the code is:

class Program
{
    static Action<string> OnReceivedAction = OnReceived;

    static void Main(string[] args)
    {
        Connect();
        Console.ReadLine();
    }

    private static async void Connect()
    {
        var hubConnectionBuilder = new HubConnectionBuilder();

        var hubConnection = hubConnectionBuilder.WithUrl("http://localhost:60211/timeHub").Build();

        await hubConnection.StartAsync();

        var on = hubConnection.On("ReceiveMessage", OnReceivedAction);

        Console.ReadLine();
        on.Dispose();
        await hubConnection.StopAsync();
    }

    static void OnReceived(string message)
    {
        System.Console.WriteLine($"{message}");
    }
}

我尝试调试应用程序.客户端成功连接到 TimeHub.当客户端连接时,Clients.All 中的连接数从 0 变为 1.但是,当 await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString()); 被执行时,TimeHub 中的 UpdateTime 函数 没有被执行,客户端也没有收到任何消息.

I tried debugging the application. The client got connected to the TimeHub succesfully. The no of connections in Clients.All changed from 0 to 1, when the client got connected. But, when await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString()); is executed, the UpdateTime function in TimeHub is not getting executed and the client is not getting any message.

我尝试使用 "UpdateTime""SendMessage""ReceiveMessage" 作为 Clients.All.SendAsync 中的方法TimeRelay 类中.没有任何效果.有人能指出我在这方面的错误吗.

I tried using "UpdateTime", "SendMessage", and "ReceiveMessage" as method in Clients.All.SendAsync in TimeRelay class. Nothing worked. Could someone point out my mistake in this.

推荐答案

我开始使用它,我想我会在这里回答它.感谢@TaoZhou 的提示.

I got it to work and thought I will answer it here. Thanks @TaoZhou for the tip.

我的错误是从服务器发送UpdateTime"并在客户端等待ReceiveMessage".

My mistake was sending "UpdateTime" from server and waiting on "ReceiveMessage" at the client.

理想情况下,代码应如下所示:

Ideally the code should look like the following:

SignalR 服务器:
await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString());

SignalR Server:
await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString());

SignalR 客户端:
var on = hubConnection.On("UpdateTime", OnReceivedAction);

SignalR Client:
var on = hubConnection.On("UpdateTime", OnReceivedAction);

在这种情况下,从服务器发送的任何消息都会立即在客户端收到.
请参阅问题中提供的代码以获取更多信息.

In this case any message send from the server would be received at the client instantly.
Please refer the code provided in the question for more info.

这篇关于调用 SignalR Hub 不适用于 Asp.Net Core Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:01