Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.IO;
- using System.Net.Sockets;
- namespace EinfacherWebserver
- {
- public class Request
- {
- private TcpClient c;
- private string localPath;
- public string LocalUrl { get; private set; }
- public string Verb { get; private set; }
- public string HttpVersion { get; private set; }
- public List<string> Header { get; private set; }
- public Request(TcpClient c, string localPath)
- {
- this.c = c;
- this.localPath = localPath;
- Header = new List<string>();
- Process();
- }
- private void Process()
- {
- var r = new StreamReader(c.GetStream());
- var w = new StreamWriter(c.GetStream());
- try
- {
- HandleRequest(r, w);
- }
- catch (Exception e)
- {
- Failed(w);
- }
- finally
- {
- w.Close();
- r.Close();
- c.Close();
- }
- }
- private void HandleRequest(StreamReader r, StreamWriter w)
- {
- string request = r.ReadLine();
- if (request != null)
- {
- string[] tokens = request.Split(' ');
- Verb = tokens[0].ToUpper();
- LocalUrl = tokens[1];
- HttpVersion = tokens[2];
- ReadHeader(r);
- string file = Path.Combine(
- Path.GetFullPath(localPath),
- LocalUrl.TrimStart('/'));
- string text = File.ReadAllText(file);
- Succeeded(w, Path.GetExtension(LocalUrl).TrimStart('.'));
- w.Write(text);
- }
- }
- private void Succeeded(StreamWriter stream, string extention)
- {
- stream.WriteLine("HTTP/1.0 200 OK");
- stream.WriteLine("Content-Type: text/" + extention);
- stream.WriteLine("Connection: close");
- stream.WriteLine("");
- }
- private void Failed(StreamWriter stream)
- {
- stream.WriteLine("HTTP/1.0 404 not found");
- stream.WriteLine("Connection: close");
- stream.WriteLine("");
- }
- private void ReadHeader(StreamReader r)
- {
- //DO SOMETHING
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment