csharp,using System;,using System.Net;,using System.Net.Sockets;class WebServer,{, static void Main(), {, TcpListener server = null;, try, {, IPAddress ipAddress = IPAddress.Parse("127.0.0.1");, server = new TcpListener(ipAddress, 8000);, server.Start();, Console.WriteLine("Server started..."); while (true), {, TcpClient client = server.AcceptTcpClient();, NetworkStream stream = client.GetStream();, byte[] buffer = new byte[256];, int bytesRead = stream.Read(buffer, 0, buffer.Length);, string request = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);, Console.WriteLine("Request: " + request); string response = "HTTP/1.1 200 OK,Content-Type: text/htmlHello, World!";, byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);, stream.Write(responseBytes, 0, responseBytes.Length);, stream.Close();, }, }, catch (SocketException se), {, Console.WriteLine("SocketException: " + se);, }, finally, {, server.Stop();, }, },},
“
C# 代码实现简单 Web 服务器
在 C# 中,你可以使用多种方式来创建一个简单的 Web 服务器,以下是一个使用 .NET 框架中的HttpListener
类来实现的示例,这个示例将展示如何创建一个基本的 HTTP 服务器,该服务器能够处理简单的 GET 请求并返回响应。
步骤一:创建项目和添加命名空间引用
1、打开 Visual Studio 并创建一个新的控制台应用程序项目。
2、在项目的Program.cs
文件中,添加必要的命名空间引用:
using System; using System.Net; using System.Text; using System.Threading.Tasks;
步骤二:编写 Web 服务器代码
在Program.cs
文件中,编写以下代码来创建和启动一个基本的 Web 服务器:
class Program { static void Main(string[] args) { // 创建 HttpListener 实例并指定前缀(即监听的 URL) HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); // 启动监听器 listener.Start(); Console.WriteLine("Server started at http://localhost:8080/"); while (true) { // 等待客户端请求 HttpListenerContext context = listener.GetContext(); Task.Run(() => ProcessRequest(context)); } } static async Task ProcessRequest(HttpListenerContext context) { // 获取请求的 URL 和查询字符串参数 string requestUrl = context.Request.RawUrl; string responseString = "Hello, World!"; if (requestUrl.Contains("/hello")) { responseString = "Hello, you requested /hello!"; } else if (requestUrl.Contains("/time")) { responseString = $"Current server time is: {DateTime.Now}"; } // 设置响应内容类型和编码 context.Response.ContentType = "text/plain"; context.Response.ContentEncoding = Encoding.UTF8; // 写入响应内容到输出流 using (System.IO.StreamWriter writer = new System.IO.StreamWriter(context.Response.OutputStream)) { await writer.WriteAsync(responseString); } // 发送响应 context.Response.Close(); } }
代码解释
HttpListener:这是一个用于监听 HTTP 请求的类,我们通过指定前缀(例如http://localhost:8080/
)来告诉它监听哪个 URL。
GetContext:这个方法会阻塞调用线程,直到有新的 HTTP 请求到达,一旦有请求到达,它会返回一个HttpListenerContext
对象,其中包含了请求的所有信息。
ProcessRequest:这是一个异步方法,用于处理每个传入的请求,根据请求的 URL,我们可以决定返回不同的响应内容,在这个例子中,如果请求包含/hello
,则返回 "Hello, you requested /hello!";如果包含/time
,则返回当前服务器时间。
Response:我们设置了响应的内容类型为text/plain
,并使用StreamWriter
将响应内容写入输出流,调用Response.Close()
方法发送响应给客户端。
运行服务器
1、保存并编译项目。
2、运行可执行文件或在 Visual Studio 中按 F5 键启动调试模式。
3、打开浏览器,访问http://localhost:8080/
,你应该会看到 "Hello, World!" 的消息,尝试访问http://localhost:8080/hello
和http://localhost:8080/time
,看看不同的响应。
扩展功能
这个简单的 Web 服务器可以进一步扩展以支持更多的功能,
路由系统:实现更复杂的路由匹配,支持动态路径参数和通配符。
静态文件服务:允许服务器提供 HTML、CSS、JavaScript 等静态文件。
模板引擎:集成模板引擎(如 Razor)来生成动态 HTML 页面。
数据库集成:连接到数据库并提供数据驱动的 API 接口。
身份验证与授权:添加用户认证和权限管理功能。
日志记录:记录请求和响应日志,便于调试和监控。
FAQs
Q1: 如何在 C# 中使用HttpListener
处理 POST 请求?
A1: 要处理 POST 请求,你可以在ProcessRequest
方法中检查context.Request.HttpMethod
是否为POST
,如果是 POST 请求,你可以使用context.Request.InputStream
读取请求体中的数据。
if (context.Request.HttpMethod == "POST") { using (System.IO.StreamReader reader = new System.IO.StreamReader(context.Request.InputStream)) { string postData = await reader.ReadToEndAsync(); // 处理 postData... } responseString = "Received a POST request with data: " + postData; }
Q2: 如何让 C# Web 服务器支持 HTTPS?
A2: 要让 C# Web 服务器支持 HTTPS,你需要生成 SSL 证书并将其绑定到HttpListener
,以下是一个简单的示例:
1、生成自签名证书(可以使用 OpenSSL 或其他工具)。
2、将证书导入到系统的受信任根证书颁发机构存储区(不推荐用于生产环境)。
3、修改代码以使用 HTTPS 前缀,并加载证书:
X509Certificate2 certificate = new X509Certificate2("path_to_your_certificate.pfx", "password"); listener.Prefixes.Add("https://localhost:443/"); listener.Start();
注意:在实际部署时,建议使用由受信任的证书颁发机构颁发的证书,而不是自签名证书。