使用C#实现一个简单的http服务器。

使用 C# 实现一个简单的 HTTP 服务器的代码示例。请注意,这只是一个基本的实现,可能需要进行修改以适应您的具体需求,例如添加身份验证、HTTPS 支持等。

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SimpleHttpServer
    class Program
        static void Main(string[] args)
            int port = 8080; // 设置端口号
            TcpListener listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            Console.WriteLine($"HTTP 服务已启动,监听端口:{port}");
            while (true)
                using (TcpClient client = listener.AcceptTcpClient())
                    HandleClient(client);
        static void HandleClient(TcpClient client)
            using (NetworkStream stream = client.GetStream())
                byte[] buffer = new byte[1024];
                int numBytesRead = stream.Read(buffer, 0, buffer.Length);
                string request = Encoding.ASCII.GetString(buffer, 0, numBytesRead);
                Console.WriteLine($"接收到请求:\n{request}");
                string[] tokens = request.Split(' ');
                string httpMethod = tokens[0];
                string httpUrl = tokens[1];
                if (httpMethod == "GET")
                    RespondWithFile(stream, httpUrl);
                    RespondWithError(stream, HttpStatusCode.NotImplemented, "不支持此 HTTP 方法");
        static void RespondWithFile(NetworkStream stream, string httpUrl)
            string filePath = "." + httpUrl;
            if (!File.Exists(filePath))
                RespondWithError(stream, HttpStatusCode.NotFound, "文件不存在");
                return;
            string fileContent = File.ReadAllText(filePath);
            byte[] responseBytes = Encoding.UTF8.GetBytes($"HTTP/1.1 200 OK\n\n{fileContent}");
            stream.Write(responseBytes, 0, responseBytes.Length);
        static void RespondWithError(NetworkStream stream, HttpStatusCode statusCode, string errorMessage)