private async Task <HttpRequest> ReadByteFromClientSocketAndBuildRequest(Socket socketAccepted)
        {
            byte[] bufferReceive = new byte[_bufferLength];

            using (var received = new MemoryStream())
            {
                while (true)
                {
                    int receiveLength = socketAccepted.Receive(bufferReceive);
                    if (receiveLength <= 0)
                    {
                        break;
                    }

                    received.Write(bufferReceive, 0, receiveLength);

                    if (receiveLength <= _bufferLength)
                    {
                        break;
                    }
                }

                string data = Encoding.UTF8.GetString(received.ToArray());

                var tempReq = await HttpTransform.BuildHttpRequest(data);

                return(tempReq);
            }
        }
예제 #2
0
        internal static async Task <HttpRequest> DoHandShaking(TcpClient clientWssAccepted, NetworkStream clientStream, byte[] wssReceivedBytes)
        {
            string      wss1stData   = Encoding.UTF8.GetString(wssReceivedBytes);
            HttpRequest firstRequest = null;

            if (Regex.IsMatch(wss1stData, "^GET", RegexOptions.IgnoreCase))
            {
                firstRequest = await HttpTransform.BuildHttpRequest(wss1stData);

                WebsocketServerHub.Register(firstRequest.UrlRelative, clientWssAccepted, clientStream);

                //do handshaking
                string swk            = Regex.Match(wss1stData, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
                string swka           = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                byte[] swkaSha1       = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
                string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);
                byte[] response       = Encoding.UTF8.GetBytes(
                    "HTTP/1.1 101 Switching Protocols\r\n" +
                    "Connection: Upgrade\r\n" +
                    "Upgrade: websocket\r\n" +
                    "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");

                await clientStream.WriteAsync(response, 0, response.Length);

                return(firstRequest);
            }

            return(firstRequest);
        }