I saw this video where the server was coded in Rust. If you're trying to learn how it works, maybe it will be useful.
Coding a Web Server in 25 Lines - Computerphile
If you want to just copy and paste the code and see it working, make sure you have an index.html
file in the project folder.
Code sample
TcpListener class description:
The System.Net.Sockets.TcpListener class provide TCP services at a higher level of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpListener is used to create a host process that listens for connections from TCP clients.
using System.Net;
using System.Net.Sockets;
using System.Text;
var tcpListener = new TcpListener(IPAddress.Loopback, 9999);
tcpListener.Start();
while (true)
{
using var handler = tcpListener.AcceptTcpClient();
await using var stream = handler.GetStream();
var reader = new StreamReader(stream);
while (true)
{
var line = reader.ReadLine();
Console.WriteLine(line);
if (string.IsNullOrWhiteSpace(line)) break;
}
const string okResponse = "HTTP/1.1 200 OK\r\n\r\n";
await stream.WriteAsync(Encoding.UTF8.GetBytes(okResponse));
var projectPath = new DirectoryInfo(Directory.GetCurrentDirectory())
.Parent!.Parent!.Parent!.FullName;
var htmlBuffer = Encoding.UTF8.GetBytes(File.ReadAllText(Path.Combine(projectPath, "index.html")));
await stream.WriteAsync(htmlBuffer);
}
Example
In the server console:
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Priority: u=0, i
Top comments (0)