Example #1
0
        /// <summary>
        /// Method is called when a new client request is received, should not be called by user!
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private static void ProcessClientRequest(object obj, HTTPServer.WebServerEventArgs e)
        {
            //DebugUtils.Print(DebugLevel.INFO, "Received a request in ProcessClientRequest method:");
            //do not use this, emtpy (null) requests will cause HTTPHeader.Parse to return null, ToString() on null object will cause a null reference exception
            //DebugUtils.Print(DebugLevel.INFO, HTTPHeader.Parse(e.rawData).ToString());

            HTTPRequest request = HTTPRequest.Parse(e.rawData);

            DebugUtils.Print(DebugLevel.INFO, request.ToString());

            HTTPHeader header = new HTTPHeader();

            header.Add("Content-Type", "text/html; charset=utf-8");
            header.Add("Connection", "close");

            string body = "Hello World!";
            string data = "HTTP/1.1 200 OK\r\n" + header.ToString() + body;

            OutPutStream(e.response, data);
        }
        public static HTTPHeader Parse(string rawHeader)
        {
            if (rawHeader == null)
            {
                return(null);
            }
            HTTPHeader header = new HTTPHeader();

            try
            {
                //Split raw data into lines
                string[] lines = rawHeader.Split(new char[] { '\n' });

                for (int i = 0; i < lines.Length; i++)
                {
                    if (lines[i] != null && lines[i].IndexOf(':') > -1)
                    {
                        //Remove line breaks and carriage returns
                        lines[i] = lines[i].Replace("\n", "").Replace("\r", "");
                        //Split at all ':', first substring is the header name
                        string headerName = lines[i].Split(new char[] { ':' })[0];
                        //Substring after ':' is headerValue
                        string headerValue = lines[i].Substring(lines[i].IndexOf(':') + 2);

                        //Add header to list
                        header.Add(headerName, headerValue);
                    }
                }
            }
            catch (Exception e)
            {
                DebugUtils.Print(DebugLevel.ERROR, "Failed to parse raw data into HTTP header.");
                DebugUtils.Print(DebugLevel.ERROR, e.StackTrace);
            }
            return(header);
        }