Error 502 Bad Gateway is reported when a C# client connects to WebSocket

I glitch to write a chat server, including registration, login, connection chat and other functions, I use C# to write the client, now the registration, login functions are normal, but when I log in successfully and try to connect to the server, the error 502 Bad Gateway has been reported. Even if I modify the “User-Agent”, it doesn’t help. How should this be solved

try connecting from a browser and compare the requests made

ok another note: see about whether the project gets the request and sends a response, to tell if there’s a problem in glitch’s own http gateway.

edit to add a weird thing: if your server side app refuses an upgrade, glitch will send out a 502 to the client instead of the response from your app

The browser access is normal, but the client cannot be connected

The console printed information during registration and login, but the subsequent WebSocket connection function did not print any information, I deployed this project to vercel, the client can be connected, so error 502 is not for some security reasons to make a limitation?

if the browser can connect, then compare the requests made by the browser and the native client. maybe they’re sending some headers different that glitch is somehow sensitive to.

I don’t have any info about this being a security issue. it could be a functionality limitation in e.g. the software that figures out which project to send an incoming request to

I copied the title of the browser side access, but still couldn’t connect to the server, and I saw people in similar situations with no solution

what’s the title?

I’m suggesting you compare the request at the HTTP level. do you have a way to see that from the native client?

Login and registration is to use HttpClient, function is normal, here to Add the title: DefaultRequestHeaders.Add(“User-Agent”, “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0”);

The connection server function is ClientWebSocket. There is no title to set. The error is in this code: await webSocket.ConnectAsync(uri, _cts.Token);

looks like there’s a variant that also takes an http invoker, could you use that and intercept the http request message and print it out?

        public WebSocketClient()
        {
            ServerUrl.TypeUrl = UrlType.Glitch;
            _webSocket = new ClientWebSocket();
            _cts = new CancellationTokenSource();
            _httpClient = new HttpClient(new HttpClientHandler());

            string useragent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0";

            _httpClient.DefaultRequestHeaders.Add("User-Agent", useragent);
            _httpClient.DefaultRequestHeaders.Add("Host", "useful-eager-fireman.glitch.me");
            _httpClient.DefaultRequestHeaders.Add("Authorization", "secret");

            _webSocket.Options.SetRequestHeader("UserAgent", useragent);
        }

This is my client initialization code. Are there any other Settings for WebSocket?

did you leave out the - in UserAgent

In webSocket, it really is “UserAgent”, not “User-Agent”.

explain…

isn’t it said that web socket upgrade requests are just http requests?

        public WebSocketClient()
        {
            ServerUrl.TypeUrl = UrlType.Glitch;
            _webSocket = new ClientWebSocket();
            _cts = new CancellationTokenSource();
            _httpClient = new HttpClient(new HttpClientHandler());

            string useragent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0";

            _httpClient.DefaultRequestHeaders.Add("User-Agent", useragent);
            _httpClient.DefaultRequestHeaders.Add("Host", "useful-eager-fireman.glitch.me");
            _httpClient.DefaultRequestHeaders.Add("Authorization", "secret");

            _webSocket.Options.SetRequestHeader("UserAgent", useragent);
        }

        /// <summary>
      ///Can register normally
        /// </summary>
        public async Task<string> RegisterAsync(string username, string password)
        {
            var registerData = new RegisterData { username = username, password = password };
            var content = new StringContent(jsonSerializer.Serialize<RegisterData>(registerData), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await _httpClient.PostAsync(httpsregister, content);
            response.EnsureSuccessStatusCode(); 
            if (response.IsSuccessStatusCode)
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
///Can log in normally
        /// </summary>
        public async Task<string> LoginAsync(string username, string password)
        {
            var loginData = new RegisterData { username = username, password = password };
            var content = new StringContent(jsonSerializer.Serialize<RegisterData>(loginData), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await _httpClient.PostAsync(httpslogin, content, CancellationToken.None);
            response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                var jsonResponse = await response.Content.ReadAsStringAsync();
                HandshakeToken data = jsonSerializer.Deserialize<HandshakeToken>(jsonResponse);
                _token = data.token;
                _username = username;
            }
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        ///Unable to connect to the server
        /// </summary>
        public async Task ConnectAsync(Uri uri)
        {
            if (string.IsNullOrEmpty(_token))
            {
                throw new InvalidOperationException("You must log in before connecting to the WebSocket server.");
            }

            try
            {
                await _webSocket.ConnectAsync(uri, _cts.Token); 
***//We've been reporting 502 errors here***

                var handshakeMessage = new Handshake
                {
                    type = "handshake",
                    username = _username,
                    token = _token
                };
                var handshakeBuffer = jsonSerializer.SerializeToByteArray(handshakeMessage);
                await _webSocket.SendAsync(new ArraySegment<byte>(handshakeBuffer), WebSocketMessageType.Text, true, _cts.Token);

                _ = ReceiveMessagesAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to connect: {ex.Message}");
                throw; 
            }
        }

This is part of the program of the client. The two functions of registration and login can connect to the giltch server, but when I changed to websocket connection, it kept reminding me of “502 Bad Gateway”.

what did you see to make you believe that it “really is ‘UserAgent’, not ‘User-Agent’”?