c# 创建简单的HttpListener服务器
时间: 2024-01-13 10:03:19 浏览: 48
下面是一个使用C#创建简单的HttpListener服务器的示例代码:
```csharp
using System;
using System.Net;
using System.Text;
public class SimpleHttpServer
{
public static void Main(string[] args)
{
// 设置监听的地址和端口号
string url = "http://localhost:8080/";
// 创建HttpListener对象
HttpListener listener = new HttpListener();
// 添加要监听的地址
listener.Prefixes.Add(url);
// 开始监听
listener.Start();
Console.WriteLine("Server is running...");
while (true)
{
// 等待客户端请求
HttpListenerContext context = listener.GetContext();
// 获取请求对象
HttpListenerRequest request = context.Request;
// 获取请求的HTTP方法(GET, POST等)
string httpMethod = request.HttpMethod;
// 获取请求的URL
string urlRequest = request.Url.ToString();
// 获取请求的内容
string requestBody = new System.IO.StreamReader(request.InputStream, request.ContentEncoding).ReadToEnd();
// 构建响应内容
string responseBody = "<html><body><h1>Hello, World!</h1></body></html>";
// 将响应内容转换为字节数组
byte[] buffer = Encoding.UTF8.GetBytes(responseBody);
// 设置响应状态码
context.Response.StatusCode = 200;
// 设置响应内容长度
context.Response.ContentLength64 = buffer.Length;
// 发送响应内容
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
// 关闭响应
context.Response.OutputStream.Close();
}
}
}
```
这个例子创建一个HttpListener对象,并设置要监听的地址和端口号。然后使用while循环等待客户端请求。当有客户端请求到达时,它获取请求对象,并从请求对象中获取HTTP方法,URL和内容。然后构建响应内容,并将其发送回客户端。