Ejemplo n.º 1
0
        public void Listen(string Address, int Port)
        {
            if (Address.ToLower() == "localhost")
            {
                Address = "127.0.0.1";
            }
            listener = new TcpListener(IPAddress.Parse(Address), Port);
            listener.Start();

            new Thread(() =>
            {
                while (true)
                {
                    using (Socket socket = listener.AcceptSocket())
                    {
                        if (socket.Connected)
                        {
                            byte[] bytes  = new byte[1024];
                            int received  = socket.Receive(bytes, bytes.Length, 0);
                            string buffer = Encoding.UTF8.GetString(bytes);

                            string[] sections = buffer.Split(System.Environment.NewLine.ToCharArray());

                            Request req = new Request();
                            for (int i = 0; i < sections.Length; i++)
                            {
                                string section = sections[i].Trim();
                                Match matchKey = Regex.Match(section, "^(.+?)(?=([ :]))");
                                if (matchKey.Success)
                                {
                                    string key   = matchKey.Value;
                                    string value = section.Replace(key, "").TrimStart(' ', ':');
                                    SetRequestHeader(key, value, ref req);
                                }
                            }

                            // Find the callback.
                            Responder responder = responders.FirstOrDefault(r => r.Verb == req.Verb && Regex.IsMatch(req.Path, r.Expression));

                            if (!responder.IsEmpty())
                            {
                                responder.Callback(req, new Response(socket, 200));
                            }
                            else if (FileExists(req.Path))
                            {
                                ServeFile(req, new Response(socket, 200));
                            }
                            else
                            {
                                NotFoundCallBack(req, new Response(socket, 404));
                            }
                        }
                    }
                }
            }).Start();
        }