我正在try 使用.Net Core Web API(服务器端)和控制台应用程序(客户端)来实现SignalR,以了解其工作原理.
下面是我的starp.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");
});
}
以下是我的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);
}
}
I am expecting Result :
ConnectionId
Hey
But I am getting:
ConnectionId