本示例教程详细介绍如何使用C#编程语言快速搭建一个简单的Web服务器。适合初学者学习基本概念与实践技巧。
C#简单Web服务器开发实例可以通过HttpListener来实现。下面是一个简单的示例:
1. 首先,在项目中添加对System.Net.HttpListener的引用。
2. 创建一个新的HTTP监听器,并设置要监听的URL前缀,如http://localhost:8080/。
3. 开始监听传入请求并处理它们。
以下是实现步骤中的关键代码片段:
```csharp
using System;
using System.Net;
class SimpleWebServer {
static void Main() {
HttpListener listener = new HttpListener();
listener.Prefixes.Add(http://localhost:8080/);
listener.Start();
Console.WriteLine(Listening...);
while (true) {
HttpListenerContext context = listener.GetContext();
// 处理请求
HandleRequest(context);
}
}
private static void HandleRequest(HttpListenerContext context) {
var response = context.Response;
string s = Hello, world!;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
}
```
以上代码段展示了一个基础的C# Web服务器实现,它使用HttpListener来监听HTTP请求,并返回一个简单的HTML页面作为响应。