Пример #1
0
        public static void Handshake(Stream stream, Uri uri)
        {
            string key = GetNonce();

            string handshake =
                $"GET /chat HTTP/1.1\r\n" +
                $"Host: {uri.Host}:{uri.Port}\r\n" +
                $"Upgrade: websocket\r\n" +
                $"Connection: Upgrade\r\n" +
                $"Sec-WebSocket-Key: {key}\r\n" +
                $"Sec-WebSocket-Version: 13\r\n" +
                "\r\n";

            byte[] encoded = Encoding.ASCII.GetBytes(handshake);
            stream.Write(encoded, 0, encoded.Length);

            string responseHeader = stream.ReadHttpHeader();
            string acceptHeader   = "Sec-WebSocket-Accept: ";
            int    startIndex     = responseHeader.IndexOf(acceptHeader) + acceptHeader.Length;
            int    endIndex       = responseHeader.IndexOf("\r\n", startIndex);
            string responseKey    = responseHeader.Substring(startIndex, endIndex - startIndex);

            string expectedResponse = Nonce.Hash(key);

            if (responseKey != expectedResponse)
            {
                throw new WebSocketException(WebSocketError.HeaderError, $"Response key incorrect, Response:{responseKey} Expected:{expectedResponse}");
            }
        }
Пример #2
0
        static void AcceptHandshake(Stream stream, string msg)
        {
            var responseBuffer = new MemoryStream();

            string key     = GetKey(msg);
            string keyHash = Nonce.Hash(key);

            CreateResponse(keyHash, responseBuffer);
            responseBuffer.WriteTo(stream);
        }