在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響應。這只是一個簡單的示例,實際應用中可以根據需要進行更復雜的邏輯處理和路由配置。