Esempio n. 1
0
        static void Main(string[] args)
        {
            if (args.Length == 4)
            {
                string            hostname = args[0];
                int               port     = int.Parse(args[1]);
                HTTPRequestMethod command  = (HTTPRequestMethod)Enum.Parse(typeof(HTTPRequestMethod), args[2].ToUpper());
                string            filename = args[3];

                IPAddress[] ipv4Addresses = Array.FindAll(Dns.GetHostEntry(hostname).AddressList, a => a.AddressFamily == AddressFamily.InterNetwork);

                filename = filename.Replace('\\', '/');

                using (Socket client = new Socket(SocketType.Stream, ProtocolType.Tcp))
                {
                    HTTPRequest req = new HTTPRequest();
                    req.Header.ProtocolVersion  = "HTTP/1.1";
                    req.Header.ResourceLocation = filename;

                    bool isValid = false;
                    if (command == HTTPRequestMethod.GET)
                    {
                        req.Header.Method = HTTPRequestMethod.GET;
                        isValid           = true;
                    }
                    else if (command == HTTPRequestMethod.PUT)
                    {
                        req.Header.Method = HTTPRequestMethod.PUT;

                        if (File.Exists(filename) == true)
                        {
                            using (FileStream fs = new FileStream(filename, FileMode.Open))
                            {
                                using (BinaryReader bw = new BinaryReader(fs))
                                {
                                    req.RawBody = bw.ReadBytes((int)fs.Length);
                                }
                            }
                            isValid = true;
                        }
                    }

                    if (isValid == true)
                    {
                        client.Connect(new IPEndPoint(ipv4Addresses[0], port));
                        client.Send(req.GetResponseStream());
                        Console.WriteLine(ASCIIEncoding.GetEncoding(0).GetString(ReadResponse(client)));
                    }
                }
            }

            else
            {
                Console.WriteLine("YetAnotherWebServer hostname port command filename");
            }
        }