Ejemplo n.º 1
0
 /// <summary>
 /// Constructs the appropriate response based on the supplied RequestHeader
 /// </summary>
 /// <param name="header"></param>
 /// <param name="response"></param>
 public void HandleRoute(RequestHeader header, Response response)
 {
     //predefined routes
     if (header.Route == "/echo")
     {
         //for debugging
         response.SetBody(header.ToString());
     }
     else if (header.Route == "/")
     {
         response.SetBody(File.ReadAllText(Constants.DEFAULT_ROUTE));
     }
     else
     {
         if (header.Route.Length > 0)
         {
             //PA 3 TODO: fetch the file from the file system and attach it
             //in either TEXT or BINIARY form depending on file type.  Text-based
             //files will be TEXT (e.g. HTML, CSS, JavaScript, etc.) whereas everything
             //else would be BINARY.
             //Functions that you might find helpful:
             //Path.Join for locating the file on your file system (NO HARD CODING!)
             //File.ReadAllBytes for reading BINARY files
             //File.ReadAllText for reading TEXT files
             //SetMimeType (see above) for correctly setting the MIME type of your response
         }
         else
         {
             //404 not found
             response.Header.ResponseCode = 404;
             response.SetBody(File.ReadAllText(Constants.ERROR_404));
         }
     }
 }
Ejemplo n.º 2
0
        private void ReceiveData(object socket)
        {
            RequestHeader requestHeader = new RequestHeader();
            var           clientSocket  = socket as Socket;

            Byte[]     buffer        = new Byte[1024];
            IPEndPoint clientep      = (IPEndPoint)clientSocket.RemoteEndPoint;
            string     clientMessage = string.Empty;

            try
            {
                clientSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                clientMessage = System.Text.Encoding.Default.GetString(buffer);
                Console.WriteLine(clientMessage);
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("<html><head><title>Server throw an exception:{1}</title></head><body>{0}</body></html>", ex.Message, ex.GetType().FullName);
                var data = Encoding.ASCII.GetBytes(sb.ToString());
                clientSocket.Send(data, data.Length, SocketFlags.None);
            }

            using (StringReader sr = new StringReader(clientMessage))
            {
                StringBuilder sb   = new StringBuilder();
                var           line = sr.ReadLine();
                if (!string.IsNullOrWhiteSpace(line))
                {
                    string[] headerInfo = line.Split(new char[] { ' ' });
                    if (headerInfo.Length == 3)
                    {
                        requestHeader.SetHeader(headerInfo[0], headerInfo[1], headerInfo[2]);
                        switch (requestHeader.Method.ToUpper())
                        {
                        case "GET":
                            for (line = sr.ReadLine(); !string.IsNullOrWhiteSpace(line); line = sr.ReadLine())
                            {
                                string[] tokens = line.Split(new string[] { ": " }, StringSplitOptions.None);
                                if (tokens.Length == 2)
                                {
                                    requestHeader.Properties.Add(tokens[0], tokens[1]);
                                }
                                else
                                {
                                    Console.WriteLine(line);
                                }
                            }
                            writesuccess(sb, requestHeader);
                            sb.AppendFormat("<html><head><title>You request {1}</title></head><body><h2>Welcome to aocwes http server</h2>{0}<h3><div><h3>Your requested content:</h3>{2}</div>Author: <a href='mailto:flyear.cheng2gmail.com'>Flyear</a></h3></body></html>", requestHeader.ToString(), requestHeader.Url, clientMessage);
                            var data = Encoding.ASCII.GetBytes(sb.ToString());
                            clientSocket.Send(data, data.Length, SocketFlags.None);
                            Console.WriteLine(string.Format("ClientAddress:{0}, Request Url:{1}", clientep.Address, requestHeader.Url));
                            break;

                        case "POST":
                        case "HEAD":
                        case "PUT":
                        case "DELETE":
                        case "TRACE":
                        case "CONNECT":
                        case "OPTIONS":
                        default:
                            writesuccess(sb, requestHeader);
                            sb.AppendFormat("<html><head><title>You request {1}</title></head><body><h2>Welcome to aocwes http server</h2>{0}<h3>Author: <a href='mailto:flyear.cheng2gmail.com'>Flyear</a></h3></body></html>", requestHeader.ToString(), requestHeader.Url);
                            var data1 = Encoding.ASCII.GetBytes(sb.ToString());
                            clientSocket.Send(data1, data1.Length, SocketFlags.None);

                            break;
                        }
                    }
                    else
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            clientSocket.Shutdown(SocketShutdown.Both);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Constructs the appropriate response based on the supplied RequestHeader
        /// </summary>
        /// <param name="header"></param>
        /// <param name="response"></param>
        public void HandleRoute(RequestHeader header, Response response)
        {
            //predefined routes
            if (header.Route == "/echo")
            {
                //for debugging
                response.SetBody(header.ToString());
            }
            else if (header.Route == "/")
            {
                Dictionary <string, string> testDict = new Dictionary <string, string>();
                testDict.Add("test_cookie", "Hello, World!");
                response.SetBody(File.ReadAllText(Constants.DEFAULT_ROUTE));
                response.Header.setCookieData(testDict);
            }
            else
            {
                if (header.Route.Length > 0)
                {
                    Console.WriteLine(header.Route);
                    SetMimeType(header.Route, response.Header);
                    string path = Path.Join(System.AppDomain.CurrentDomain.BaseDirectory, "public");
                    path = Path.Join(path, header.Route);
                    switch (response.Header.ContentType)
                    {
                    case ContentType.HTML:
                        response.SetBody(File.ReadAllText(path));
                        break;

                    case ContentType.CSS:
                        response.SetBody(File.ReadAllText(path));
                        break;

                    case ContentType.JPEG:
                        response.SetBody(File.ReadAllBytes(path));
                        break;

                    case ContentType.X_Icon:
                        response.SetBody(File.ReadAllBytes(path));
                        break;

                    case ContentType.CSV:
                        response.SetBody(File.ReadAllText(path));
                        break;

                    case ContentType.JavaScript:
                        response.SetBody(File.ReadAllText(path));
                        break;

                    case ContentType.JSON:
                        response.SetBody(File.ReadAllText(path));
                        break;

                    case ContentType.MP3:
                        response.SetBody(File.ReadAllBytes(path));
                        break;

                    case ContentType.MP4:
                        response.SetBody(File.ReadAllBytes(path));
                        break;

                    case ContentType.OGG:
                        response.SetBody(File.ReadAllBytes(path));
                        break;

                    case ContentType.PNG:
                        response.SetBody(File.ReadAllBytes(path));
                        break;

                    case ContentType.Text:
                        response.SetBody(File.ReadAllText(path));
                        break;

                    case ContentType.WAV:
                        response.SetBody(File.ReadAllBytes(path));
                        break;

                    case ContentType.GIF:
                        response.SetBody(File.ReadAllBytes(path));
                        break;

                    case ContentType.TS:
                        response.SetBody(File.ReadAllBytes(path));
                        break;

                    case ContentType.m3u8:
                        response.SetBody(File.ReadAllText(path));
                        break;

                    default:
                        response.SetBody(File.ReadAllBytes(path));
                        break;
                    }
                }
                else
                {
                    //404 not found
                    response.Header.ResponseCode = 404;
                    response.SetBody(File.ReadAllText(Constants.ERROR_404));
                }
            }
        }