c#开发webserver
时间: 2024-09-22 20:05:55 浏览: 51
在C#中,你可以使用.NET Framework提供的HttpListener类来创建一个简单的Web服务器。HttpListener是一个用于监听HTTP请求的小型、轻量级组件,它允许应用程序作为网络服务器运行。以下是基本步骤:
1. **引用命名空间**:
首先,你需要添加System.Net.HttpListener命名空间到你的项目中。
```csharp
using System.Net.HttpListener;
```
2. **初始化并开启监听器**:
创建HttpListener实例,并设置其属性如端口号等,然后启用监听。
```csharp
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
```
这里,`8080`通常是默认的测试端口,可以根据需要修改。
3. **处理请求**:
使用事件处理机制来监听新的请求,并提供相应的响应。
```csharp
listener.GetInvocationList().ForEach(InvokeRequest);
private void InvokeRequest(object sender, EventArgs e)
{
HttpListenerContext context = ((HttpListener)sender).Context;
// 读取请求信息,例如路径、方法和请求体
string requestPath = context.Request.Url.LocalPath;
string requestBody = new StreamReader(context.Request.InputStream).ReadToEnd();
// 根据请求路径返回适当的响应
string responseContent = HandleRequest(requestPath);
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.ContentType = "text/plain";
using (var writer = new StreamWriter(context.Response.OutputStream))
{
writer.Write(responseContent);
}
}
private string HandleRequest(string requestPath) // 这里可以写你处理不同URL的逻辑
{
//...
}
```
4. **关闭监听器**:
当不再需要服务时,记得停止并关闭监听器。
```csharp
listener.Stop();
listener.Close();
```
阅读全文
相关推荐

















