SignalR C#客户端HubConnection.On方法不起作用



我正在尝试使用.Net Core Web API(服务器端(和Console应用程序(客户端(来实现SignalR,以了解其工作原理。

这是我的startup.cs代码:

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "SignalR", Version = "v1" });
});
//Service for SignalR
services.AddSignalR();
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SignalR v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseCors(o=>o.AllowAnyOrigin());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
//Endpoint map for ChatHub, which I've created
endpoints.MapHub<ChatHub>("/chathub");
});
}  

这是我的聊天中心课程:

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

这是我的控制台应用程序(创建为SignalR客户端(:

static async Task Main(string[] args)
{
try
{
HubConnection connection = new HubConnectionBuilder().WithUrl("https://localhost:44340/chathub").WithAutomaticReconnect().Build();
await connection.StartAsync();
if(connection.State == HubConnectionState.Connected)
{
Console.WriteLine("Connected ... Please type message now");
var message = "Hey";
//Getting hit to SendMessage method defined in  ChatHub Class
await connection.InvokeAsync("SendMessage", message);
Console.WriteLine(connection.ConnectionId);
/*
Connection.On is not working and unable to writeline on console.
I am expecting result Hey on Console.
*/
connection.On<string>("ReceiveMessage", m =>
{
Console.WriteLine(m);
});
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

我期待结果:ConnectionId

但我得到了:ConnectionId

由于connection.On注册事件太晚,SignalR在.Net Core Web API上广播完成。所以你无法得到信息。

您可以将connection.On注册事件移动到connection.InvokeAsync方法之前,然后您可以看到"嘿"消息。

// ...
// Register event
connection.On<string>("ReceiveMessage", m =>
{
Console.WriteLine(m);
});
if(connection.State == HubConnectionState.Connected)
{
Console.WriteLine("Connected ... Please type message now");
var message = "Hey";    
await connection.InvokeAsync("SendMessage", message);
Console.WriteLine(connection.ConnectionId);    
}
// Result:
// Connected ... Please type message now
// Hey
// ConnectionId

如果您希望ConnectionId消息先于Hey消息,您可以更改此设置。

// ...
// Register event
connection.On<string>("ReceiveMessage", m =>
{
Console.WriteLine(m);
});
if(connection.State == HubConnectionState.Connected)
{
Console.WriteLine("Connected ... Please type message now");
var message = "Hey";
// call async method and wait later
var task = connection.InvokeAsync("SendMessage", message);
Console.WriteLine(connection.ConnectionId);    
// wait SendMessage
await task;
}
// Result:
// Connected ... Please type message now
// ConnectionId
// Hey

最新更新