用 C# 自己动手编写一个 Web 服务器
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class SimpleWebServer
{
private const int Port = 8080;
public static void Main()
{
TcpListener listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
Console.WriteLine($"Server started at http://localhost:{Port}/");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
HandleClientAsync(client).Wait();
}
}
private static async Task HandleClientAsync(TcpClient client)
{
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
StreamWriter writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true };
try
{
// 读取请求行
string requestLine = await reader.ReadLineAsync();
if (string.IsNullOrEmpty(requestLine))
return;
Console.WriteLine($"Received request: {requestLine}");
// 解析请求行(为了简化,这里只处理GET请求)
string[] parts = requestLine.Split(' ');
if (parts.Length != 3 || parts[0] != "GET")
{
SendErrorResponse(writer, 400, "Bad Request");
return;
}
string path = parts[1];
if (path != "/")
{
SendErrorResponse(writer, 404, "Not Found");
return;
}
// 发送响应
SendResponse(writer, 200, "OK", "<html><body><h1>Hello, World!</h1></body></html>");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
SendErrorResponse(writer, 500, "Internal Server Error");
}
finally
{
client.Close();
}
}
private static void SendResponse(StreamWriter writer, int statusCode, string statusMessage, string content)
{
writer.WriteLine($"HTTP/1.1 {statusCode} {statusMessage}");
writer.WriteLine("Content-Type: text/html; charset=UTF-8");
writer.WriteLine($"Content-Length: {content.Length}");
writer.WriteLine();
writer.Write(content);
}
private static void SendErrorResponse(StreamWriter writer, int statusCode, string statusMessage)
{
string content = $"<html><body><h1>{statusCode} {statusMessage}</h1></body></html>";
SendResponse(writer, statusCode, statusMessage, content);
}
}