using System;
using System.Net;
using System.Text;
class SimpleWebServer
{
public static void Main()
{
// 创建一个HttpListener实例,并添加前缀来监听特定的URL
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Listening for connections on http://localhost:8080/");
try
{
while (true)
{
// 等待接收请求
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// 获取请求的URL
string url = request.Url.ToString();
Console.WriteLine($"Received request for {url}");
// 准备响应内容
string responseString = "<html><body>Hello, World!</body></html>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
// 设置响应头和内容长度
HttpListenerResponse response = context.Response;
response.ContentLength64 = buffer.Length;
response.ContentType = "text/html";
// 将响应内容写入输出流
using (System.IO.Stream output = response.OutputStream)
{
output.Write(buffer, 0, buffer.Length);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
listener.Stop();
}
}
}
http://localhost:8080/上的所有请求。HttpListenerContext对象。text/html,表示返回的是HTML内容。这个示例代码创建了一个简单的HTTP服务器,监听http://localhost:8080/,并对于每个请求返回一个简单的HTML页面。
上一篇:c# bouncycastle
下一篇:c# rectangle
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站