Ale*_*lex 5 c# signalr .net-core asp.net-core asp.net-core-webapi
我是SignalR的新手。我正在尝试设置一个Asp.Net Core WebAPI,以便其他客户端可以使用SignalR连接到它并获取实时数据。我的Hub类是:
public class TimeHub : Hub
{
public async Task UpdateTime(string message)
{
await Clients.All.SendAsync("ReceiveMessage", message);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个中继课程,如下所示:
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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
启动类:
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();
}
Run Code Online (Sandbox Code Playgroud)
客户端是一个控制台应用程序,代码为:
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}");
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试调试该应用程序。客户端TimeHub
成功连接。Clients.All
客户端连接后,连接数从0更改为1。但是,当await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString());
执行时,UpdateTime
in中的功能TimeHub
没有得到执行,并且客户端没有得到任何消息。
我在课堂上尝试使用"UpdateTime"
,"SendMessage"
和"ReceiveMessage"
作为方法。没事。有人可以指出我的错误。Clients.All.SendAsync
TimeRelay
我让它工作并想我会在这里回答它。感谢@TaoZhou 的提示。
我的错误是从服务器发送“UpdateTime”并在客户端等待“ReceiveMessage”。
理想情况下,代码应如下所示:
信号R服务器:
await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString());
SignalR 客户端:
var on = hubConnection.On("UpdateTime", OnReceivedAction);
在这种情况下,从服务器发送的任何消息都会立即在客户端收到。
请参阅问题中提供的代码以获取更多信息。