c#使用HttpListener监听HTTP请求的项目案例
时间: 2024-01-12 21:02:18 浏览: 170
PC,c#监听http请求源码,c#
以下是使用C#的HttpListener类来监听HTTP请求的示例代码:
```csharp
using System;
using System.Net;
class Program
{
static void Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Listening...");
while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = "<html><body>Hello, world!</body></html>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
}
}
```
此示例将在本地主机的8080端口上启动HttpListener,并在每个HTTP请求上返回“Hello, world!” 作为响应。你可以在浏览器中访问“http://localhost:8080/”以查看结果。注意,此示例需要管理员权限才能运行。
阅读全文