admin管理员组

文章数量:1193729

I am seeing strange behavior when trying to use both SignalR and plain old web sockets on the same Kestrel web server hosing an ASP.NET Core 8 Web API project.

The project has a REST interface, uses SignalR, and plain old web sockets were added to accommodate a client for which there is no SignalR client library.

Independently, either of them both seem to work fine. As soon as I try and use them both, all communication through both of them stops until one of them disconnects.

SignalR is being added to the builder services in Program.cs like this:

builder.Services.AddSignalR(options => {
   options.EnableDetailedErrors = true;
});

And websockets are being setup like this:

app.UseWebSockets();
app.Map("/ws", WebSocketHandler.HandleWebSocketConnection);

Here is the WebSocketHandler.HandleWebSocketConnection method:

    public static async Task HandleWebSocketConnection(HttpContext context)
    {
        if (!context.WebSockets.IsWebSocketRequest)
        {
            context.Response.StatusCode = 400; // Bad Request
            await context.Response.WriteAsync("WebSocket request expected.");
            return;
        }

        var clientId = Guid.NewGuid().ToString();
        WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
        Console.WriteLine($"Client connected: {clientId}");

        try
        {
            await HandleClientMessagesAsync(webSocket);
        }
        finally
        {
            Console.WriteLine($"Client disconnected: {clientId}");
        }
    }

I wouldn't think this is a problem because under the covers, there is only one websocket server running on one port. How can both of these be enabled on the same web server without conflicting?

本文标签: cUse BOTH SignalR and raw web sockets in ASPNET Core 8 Web API projectStack Overflow