morry2341

Webserver_Request

Nov 10th, 2022
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.Contracts;
  5. using System.IO;
  6. using System.Net.Sockets;
  7.  
  8.  
  9. namespace EinfacherWebserver
  10. {
  11. public class Request
  12. {
  13. private TcpClient c;
  14. private string localPath;
  15.  
  16. public string LocalUrl { get; private set; }
  17. public string Verb { get; private set; }
  18. public string HttpVersion { get; private set; }
  19. public List<string> Header { get; private set; }
  20.  
  21. public Request(TcpClient c, string localPath)
  22. {
  23. this.c = c;
  24. this.localPath = localPath;
  25.  
  26. Header = new List<string>();
  27.  
  28. Process();
  29. }
  30.  
  31. private void Process()
  32. {
  33. var r = new StreamReader(c.GetStream());
  34. var w = new StreamWriter(c.GetStream());
  35.  
  36. try
  37. {
  38. HandleRequest(r, w);
  39. }
  40. catch (Exception e)
  41. {
  42. Failed(w);
  43.  
  44. }
  45. finally
  46. {
  47. w.Close();
  48. r.Close();
  49. c.Close();
  50. }
  51. }
  52.  
  53. private void HandleRequest(StreamReader r, StreamWriter w)
  54. {
  55. string request = r.ReadLine();
  56. if (request != null)
  57. {
  58. string[] tokens = request.Split(' ');
  59. Verb = tokens[0].ToUpper();
  60. LocalUrl = tokens[1];
  61. HttpVersion = tokens[2];
  62.  
  63. ReadHeader(r);
  64.  
  65. string file = Path.Combine(
  66. Path.GetFullPath(localPath),
  67. LocalUrl.TrimStart('/'));
  68.  
  69. string text = File.ReadAllText(file);
  70.  
  71. Succeeded(w, Path.GetExtension(LocalUrl).TrimStart('.'));
  72.  
  73. w.Write(text);
  74. }
  75. }
  76.  
  77. private void Succeeded(StreamWriter stream, string extention)
  78. {
  79. stream.WriteLine("HTTP/1.0 200 OK");
  80. stream.WriteLine("Content-Type: text/" + extention);
  81. stream.WriteLine("Connection: close");
  82. stream.WriteLine("");
  83. }
  84.  
  85. private void Failed(StreamWriter stream)
  86. {
  87. stream.WriteLine("HTTP/1.0 404 not found");
  88. stream.WriteLine("Connection: close");
  89. stream.WriteLine("");
  90.  
  91. }
  92.  
  93. private void ReadHeader(StreamReader r)
  94. {
  95. //DO SOMETHING
  96. }
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment