Esempio n. 1
0
        public static async Task UploadStream(Stream stream, HttpRequestEntity httpRequest)
        {
            int bytesRead;

            byte[] responseBuffer = new byte[8192];

            stream.Position = 0;

            while ((bytesRead = await stream.ReadAsync(responseBuffer, 0, responseBuffer.Length)) != 0)
            {
                await httpRequest.Response.ResponseStream.WriteAsync(responseBuffer, 0, bytesRead);
            }
        }
Esempio n. 2
0
        public static async Task UploadFile(string filePath, HttpRequestEntity httpRequest)
        {
            if (File.Exists(filePath))
            {
                using (FileStream fileStream = File.OpenRead(filePath))
                {
                    httpRequest.Response.ContentLength = fileStream.Length;

                    byte[] headerBuffer = BuildHttpResponse(httpRequest);

                    await httpRequest.Response.ResponseStream.WriteAsync(headerBuffer, 0, headerBuffer.Length);

                    int    bytesRead;
                    byte[] responseBuffer = new byte[8192];

                    while ((bytesRead = await fileStream.ReadAsync(responseBuffer, 0, responseBuffer.Length)) != 0)
                    {
                        await httpRequest.Response.ResponseStream.WriteAsync(responseBuffer, 0, bytesRead);
                    }
                }
            }
        }
Esempio n. 3
0
        public static async Task <HttpRequestEntity> ParseHttpRequest(NetworkStream networkStream, TcpClient tcpClient)
        {
            HttpRequestEntity requestMessage = null;

            StreamReader streamReader = new StreamReader(networkStream);

            try
            {
                string   line = String.Empty;
                string[] parts;
                string   headerName;
                string   headerValue;
                string   content = String.Empty;

                do
                {
                    line = await streamReader.ReadLineAsync();

                    if (line == null)
                    {
                        continue;
                    }

                    if (line == "")
                    {
                        while (streamReader.Peek() != -1)
                        {
                            content += await streamReader.ReadLineAsync();
                        }
                        requestMessage.Content = content;
                        break;
                    }

                    parts = line.Split(new[] { ':' }, 2);

                    if (parts.Length == 0)
                    {
                        continue;
                    }

                    if (parts.Length > 1)
                    {
                        headerName = parts[0];

                        headerValue = parts[1].Trim();

                        requestMessage[headerName] = headerValue;
                    }
                    else
                    {
                        requestMessage = new HttpRequestEntity {
                            Client = tcpClient
                        };

                        parts = line.Split(' ');

                        requestMessage.Method = parts[0];

                        requestMessage.Version = parts[2];

                        requestMessage.QueryParameters = parts[1];
                    }
                } while (streamReader.Peek() != -1);
            }
            catch (Exception ex)
            {
                await Console.Out.WriteLineAsync(ex.Message);
            }

            if (requestMessage != null)
            {
                requestMessage.Response = new HttpResponseEntity {
                    ResponseStream = networkStream, ContentType = requestMessage.ContentType, StatusCode = HttpStatusCode.OK, Status = "OK"
                }
            }
            ;

            return(requestMessage);
        }
    }
Esempio n. 4
0
        public async Task RequestReceivedAsync(Func <HttpRequestEntity, Task> callback = null)
        {
            try
            {
                byte[] responseBuffer;

                while (true)
                {
                    try
                    {
                        using (TcpClient acceptedTcpClient = await tcpListener.AcceptTcpClientAsync().ContinueWith(t => t.Result, Token))
                        {
                            using (NetworkStream networkStream = acceptedTcpClient.GetStream())
                            {
                                Interlocked.Increment(ref receivedRequestCount);

                                HttpRequestEntity httpRequest = await HttpUtility.ParseHttpRequest(networkStream, acceptedTcpClient);

                                if (httpRequest == null)
                                {
                                    continue;
                                }

                                #region Controller

                                string   queryParams         = httpRequest.QueryParameters.ToLowerInvariant();
                                int      parameterStartIndex = queryParams.IndexOf('/', 1);
                                string   actionName          = queryParams;
                                string[] paramArray          = new string[0];

                                if (parameterStartIndex > -1)
                                {
                                    actionName = queryParams.Substring(0, parameterStartIndex);
                                    string parameters = queryParams.Substring(parameterStartIndex);
                                    paramArray = parameters.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                                }


                                if (queryParams == "/" || Path.HasExtension(queryParams))
                                {
                                    //string fileExtension = Path.GetExtension(queryParams);

                                    //if (!HttpUtility.MimeTypeDict.ContainsKey(fileExtension))
                                    //{

                                    //}

                                    string fileName = httpRequest.QueryParameters.Substring(1);

                                    if (String.IsNullOrEmpty(fileName))
                                    {
                                        fileName = "iisstart.htm";
                                    }

                                    if (fileName == "favicon.ico")
                                    {
                                        await HttpUtility.UploadStream(favicon, httpRequest);
                                    }
                                    else
                                    {
                                        string filePath = Path.Combine(SourceDirectory, fileName);

                                        await HttpUtility.UploadFile(filePath, httpRequest);
                                    }

                                    httpRequest.Handled = true;
                                }
                                else
                                {
                                    Dictionary <string, RouteInfo> routeDict = GetRoutes;

                                    if (httpRequest.Method == "POST")
                                    {
                                        routeDict = PostRoutes;
                                    }

                                    RouteInfo routeInfo;
                                    if (routeDict.TryGetValue(actionName, out routeInfo))
                                    {
                                        object[] actionParameters;
                                        if (routeInfo.ControllerInstance == null)
                                        {
                                            actionParameters    = new object[paramArray.Length + 1];
                                            actionParameters[0] = httpRequest;
                                            paramArray.CopyTo(actionParameters, 1);
                                        }
                                        else
                                        {
                                            actionParameters    = new object[paramArray.Length + 2];
                                            actionParameters[0] = routeInfo.ControllerInstance;
                                            actionParameters[1] = httpRequest;
                                            paramArray.CopyTo(actionParameters, 2);
                                        }

                                        object result = routeInfo.ActionInvoker(actionParameters);
                                    }
                                }

                                #endregion Controller

                                if (callback != null)
                                {
                                    await callback(httpRequest);
                                }

                                if (!httpRequest.Handled)
                                {
                                    responseBuffer = HttpUtility.BuildHttpResponse(httpRequest);

                                    await networkStream.WriteAsync(responseBuffer, 0, responseBuffer.Length, Token);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await Console.Out.WriteLineAsync("SERVER ------" + ex.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                await Console.Out.WriteLineAsync("SERVER ------" + ex.ToString());
            }
        }