Search code examples
c#httpwebsockettcpclienttcplistener

Cant connect Client-Server with Websockets


Im create simple web server on C# .Net Framework with Tcp-Listner Tcp-Client connections.

Now im trying to do support of Websocket connection for chat\or something else.

For sockets im use GenericHandler and js for connect them. After getting request from client

GET /socket/SocketHandler.ashx HTTP/1.1
Host: ***************
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36
Upgrade: websocket
Origin: http://************
Sec-WebSocket-Version: 13
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Sec-WebSocket-Key: aroK0T3g3A6oSxC6Qz1QDg==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

im sending response to client from server with concatenate key aroK0T3g3A6oSxC6Qz1QDg== with GUID, hash it SHA1 and convert in Base64 format for getting accept key zGccDw/PeOtlWAmdPT6HBtyywYc=

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: zGccDw/PeOtlWAmdPT6HBtyywYc=
Sec-WebSocket-Protocol: chat

but after this, client (browser) says

failed: Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value

So, what im do wrong and how to fix that?

upd: for example, im use this code for conversion

string ClientKey = socketKey;
            string GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            var conc = ClientKey + GUID;
            var buffer = Encoding.UTF8.GetBytes(conc);
            var hash1 = SHA1.Create().ComputeHash(buffer);
            var AcceptKey = System.Convert.ToBase64String(hash1);

Solution

  • I have also my own WebSocket client in C#. And It had been tested and working with ASP.NET Core.

    Then, I've tested your secure key, the result is different. I got below hash.

    QCd+628gwEVYxyYQ8ekJny8ZHCo=