我看了一些类似的问题,没有弄明白这个问题。 在我的.NET核心Web API项目中,我有一个简单的Hub。 这里是Hub。
public class NotificationHub : Hub<INotificationClient>
{
public async Task SendMessage(string user, string msg)
{
await Clients.All.ReceiveMessage(user, msg);
}
public Task SendMessageToCaller(string msg)
{
return Clients.Caller.ReceiveMessage(msg);
}
public Task SendMessageToPartner(string user, string msg)
{
return Clients.Client(user).ReceiveMessageToPartner(msg);
}
}
这里是接口
public interface INotificationClient
{
Task ReceiveMessage(string user, string msg);
Task ReceiveMessage(string msg);
Task ReceiveMessageToPartner( string msg);
}
这里是控制器的代码
[Route("[controller]")]
[ApiController]
public class NotificationsController : ControllerBase
{
private IHubContext<NotificationHub> _hub;
public NotificationsController(IHubContext<NotificationHub> hub)
{
_hub = hub;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var msg = new NotificationData { ClientId = "12345", Notification = "Somone just connected" };
await _hub.Clients.All.SendAsync("Notification", msg);
return Ok(new { Message = "Request complete" });
}
}
最后是控制台客户端代码
Console.WriteLine("Press a key to start listening");
Console.ReadKey();
Console.WriteLine("Client Listening!");
var connection = new HubConnectionBuilder()
.WithUrl("http://localhost:61514/notifications")
.Build();
connection.On<NotificationData>("Notification", (notificationData) =>
Console.WriteLine($"Somebody connected: {notificationData.ClientId}"));
connection.StartAsync().GetAwaiter().GetResult();
Console.WriteLine("Listening. Press a key to quit");
Console.ReadKey();
这里是带映射的web应用的启动过程。
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddControllers();
}
// 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.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<NotificationHub>("/Notifications");
});
}
我一直收到这个错误: System.IO.IOException: "服务器在握手开始前断开了连接 我一定是在这一过程中遗漏了什么。
更新:打开日志,得到这个错误。
dbug: Microsoft.AspNetCore.HttpException: "服务器在握手开始前断开连接 Microsoft.AspNetCore.Http.Connections.Client.HttpConnection[8] Establishing connection with server at '。http:/localhost:61514通知。'.dbug.AspNetCore.Http.Connections.Client.HttpConnection[9] 与服务器建立连接'BdROAEEQnGUeDYAW5EspRA'。Microsoft.AspNetCore.Http.Connections.Client.HttpConnection[9] 与服务器建立连接'BdROAEEQnGUeDYAW5EspRA'。Microsoft.AspNetCore.Http.Connections.Client.HttpConnection[7] 启动传输'ServerSentEvents'的Url: http:/localhost:61514notifications。...信息。Microsoft.AspNetCore.Http.Connections.Client.Internal.ServerSentEventsTransport[1] 开始传输。传输模式。传输模式:Text.dbug: Microsoft.AspNetCore.Http.Connections.Client.Internal.ServerSentEventsTransport[3] 开始接收循环。Microsoft.AspNetCore.Http.Connections.Client.Internal.ServerSentEventsTransport[9] 收到30个字节,解析SSE帧。解析SSE帧。 dbug.AspNetCore.Http.Connect.Client.Internal.ServerSentEventsTransport[9]接收到30个字节,解析SSE帧。Microsoft.AspNetCore.Http.Connections.Client.Internal.ServerSentEventsTransport[4] 接收循环停止。Microsoft.AspNetCore.Http.Connections.Client.Internal.ServerSentEventsTransport[100] 开始发送循环。Microsoft.AspNetCore.Http.Connections.Client.HttpConnection[18] 传送'ServerSentEvents'开始。Microsoft.AspNetCore.Http.Connections.Client.Internal.ServerSentEventsTransport[102] 发送循环被取消。Microsoft.AspNetCore.Http.Connections.Client.Internal.ServerSentEventsTransport[101] 发送循环停止。 未处理的异常。Info.AspNetCore.Http.Connections.Client.Internal.ServerSentEventsTransport[101] Send loop stopped: Microsoft.AspNetCore.Http.Connections.Client.HttpConnection[3] HttpConnection Started.info: Microsoft.AspNetCore.SignalR.Client.HubConnection[24] Using HubProtocol 'json v1'. System.IO.IOException: 在Microsoft.AspNetCore.SignalR.Client.HubConnection.HandshakeAsync(ConnectionState startingConnectionState, CancellationToken cancellationToken) 在Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncCore(CancellationToken cancellationToken) 在Microsoft.AspNetCore.SignalR.Client.HubConnection. 在Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncCore(CancellationToken cancellationToken) at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncInner(CancellationToken cancellationToken) at System.Threading.Tasks.ForceAsyncAwaiter.GetResult() at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsync(CancellationToken cancellationToken) at NotificationClient.Program.Main(String[] args)
所以,在喋喋不休地讨论了一整天之后,我发现了问题所在,所以我想我应该把解决方案发布在这里,以防有人遇到这个问题。
Hub端点是指向控制器的。 所以当客户机连接时,它击中控制器两次,导致服务器关闭连接。 所以我修改了这一行。
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<NotificationHub>("/Notify");
});
从 "Notifications "改成 "Notify",就像上面的代码一样 把客户端从 "Notifications "改成 "Notify
var connection = new HubConnectionBuilder()
.WithUrl("http://localhost:61514/Notify")
.ConfigureLogging(logging =>
{
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Debug);
})
.Build();
和消息开始流入。