i have aspnet core 6 app and i create websocket on the webapp :The remote party closed the WebSocket connection without completing the close handshake

i have aspnet core 6 app and i create websocket on the webapp but when i publish project i see this error : The remote party closed the WebSocket connection without completing the close handshake

app.Map("/websockify", async context => // Proxy Server
{
    var token = context.Request.Query["token"];
    context.Response.Headers.Add("Sec-WebSocket-Protocol", "binary");
    using var wsServer = await context.WebSockets.AcceptWebSocketAsync();

    using var wsClient = new ClientWebSocket();
    // wsClient.Options.SetRequestHeader("Sec-WebSocket-Protocol", "binary");
    await wsClient.ConnectAsync(new Uri($"ws://172.18.172.11:6080/?token={token}"), CancellationToken.None);

    var buffer = new byte[1024 * 1024 * 4];

    var SendToClient = Task.Run(async () =>
    {
        while (true)
        {
            var result = wsClient.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;

            if (result.MessageType == WebSocketMessageType.Close)
                break;

            var message = Encoding.Latin1.GetString(buffer, 0, result.Count);
            var bytes = Encoding.Latin1.GetBytes(message);
            await wsServer.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Binary, true, CancellationToken.None);
        }
    });


    var SendToServer = Task.Run(async () =>
    {
        while (true)
        {
            var result = wsServer.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;

            if (result.MessageType == WebSocketMessageType.Close)
                break;

            var message = Encoding.Latin1.GetString(buffer, 0, result.Count);
            var bytes = Encoding.Latin1.GetBytes(message);
            await wsClient.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Binary, true, CancellationToken.None);
        }
    });

    await Task.WhenAll(SendToServer, SendToClient);

i try new websocket on server :
on the server when use Debug mode (dotnet run ) work fine but i have problem on publish mode .
i recieve error (The remote party closed the WebSocket connection without completing the close handshake.)
i checked firewall
i checked cors and allow any cors
i checked ssl and test many times
but not fixed my problem.

Leave a Comment