c#中httpserver的使用方法是什么

c#
小億
358
2024-03-16 20:46:55

在C#中使用HttpServer,可以通過(guò).Net Framework提供的HttpListener類來(lái)實(shí)現(xiàn)。下面是一個(gè)簡(jiǎn)單的示例代碼,演示如何創(chuàng)建一個(gè)簡(jiǎn)單的HttpServer并監(jiān)聽來(lái)自客戶端的請(qǐng)求:

using System;
using System.Net;
using System.Text;

class Program
{
    static void Main()
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/"); // 設(shè)置HttpServer監(jiān)聽的地址和端口號(hào)

        listener.Start();

        Console.WriteLine("HttpServer started. Listening...");

        while (true)
        {
            HttpListenerContext context = listener.GetContext(); // 接收來(lái)自客戶端的請(qǐng)求
            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();
        }
    }
}

在上面的示例中,我們創(chuàng)建了一個(gè)簡(jiǎn)單的HttpServer,監(jiān)聽地址為http://localhost:8080/。當(dāng)接收到客戶端的請(qǐng)求后,會(huì)返回一個(gè)簡(jiǎn)單的HTML響應(yīng)。這只是一個(gè)簡(jiǎn)單的示例,實(shí)際應(yīng)用中可以根據(jù)需要進(jìn)行更復(fù)雜的邏輯處理和路由配置。

0