C#C
C#3y ago
VeQox

❔ Raw Websockets, ref alternative in async programming

 public async Task HandleUpgrade()
    {
        if (!HttpContext.WebSockets.IsWebSocketRequest)
        {
            Logger.LogInformation("Request not a websocket request");
            HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            return;
        }

        var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
        var connection = new WebSocketConnection(webSocket);
        Logger.LogInformation("Connection established");
        
        try
        {
            Room? room = null;
            Client? client = null;
            
            while (!webSocket.CloseStatus.HasValue)
            {
                var raw = await connection.ReceiveAsync();
                
                Logger.LogInformation("Received {Message} from connection[{Guid}]", raw, connection.Guid);
                
                if (raw is null) continue;

                var (webSocketClientMessage, _) = JsonUtils.Deserialize<WebSocketClientMessage>(raw);
                if (webSocketClientMessage is null) continue;
                
                await OnMessage(webSocketClientMessage, raw, connection, room, client);
            }
        }
        finally
        {
            await connection.CloseAsync();
            Logger.LogInformation("Connection closed with connection[{Guid}]", connection.Guid);
        }
    }
Was this page helpful?