在C#中使用HttpServer,可以通过.Net Framework提供的HttpListener类来实现。下面是一个简单的示例代码,演示如何创建一个简单的HttpServer并监听来自客户端的请求:
using System;
using System.Net;
using System.Text;
class Program
{
static void Main()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/"); // 设置HttpServer监听的地址和端口号
listener.Start();
Console.WriteLine("HttpServer started. Listening...");
while (true)
{
HttpListenerContext context = listener.GetContext(); // 接收来自客户端的请求
HttpListenerRequest request = context.Request;
Console.WriteLine("Request received: " + request.HttpMethod + " " + request.Url);
string responseString = "<html><head><title>HttpServer Response</title></head><body><h1>Hello from HttpServer!</h1></body></html>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
HttpListenerResponse response = context.Response;
response.ContentLength64 = buffer.Length;
response.ContentType = "text/html";
response.OutputStream.Write(buffer, 0, buffer.Length);
response.Close();
}
}
}
在上面的示例中,我们创建了一个简单的HttpServer,监听地址为http://localhost:8080/。当接收到客户端的请求后,会返回一个简单的HTML响应。这只是一个简单的示例,实际应用中可以根据需要进行更复杂的逻辑处理和路由配置。