Advertisement
xPucTu4

Web server in 25 lines of code

Oct 25th, 2024
71
0
282 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.94 KB | None | 0 0
  1. System.Net.Sockets.TcpListener listener = new(System.Net.IPAddress.Any, 8080);
  2. listener.Start();
  3. while (true)
  4. {
  5.     try
  6.     {
  7.         await Task.Run(async () =>
  8.         {
  9.             using System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
  10.             TextReader tr = new StreamReader(client.GetStream());
  11.             string requestLine = tr.ReadLine().Split(' ').Skip(1).Take(1).Single();
  12.             if (requestLine.EndsWith('/'))
  13.                 requestLine += "index.html";
  14.             TextWriter tw = new StreamWriter(client.GetStream());
  15.             await tw.WriteLineAsync("HTTP/1.1 200 OK");
  16.             await tw.WriteLineAsync();
  17.             await tw.WriteLineAsync();
  18.             byte[] responseContent = File.ReadAllBytes("./wwwroot" + requestLine);
  19.             BinaryWriter bw = new(client.GetStream());
  20.             bw.Write(responseContent);
  21.             await tw.FlushAsync();
  22.         });
  23.     }
  24.     catch { }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement