教程:
https://blog.csdn.net/qq_36702996/article/details/78892380
代码如下:
class Program
{
static void Main(string[] args)
{
HttpListener httpListener = new HttpListener();
String[] urls = { "http://localhost:7000/", "http://localhost:7001/" };
foreach (String url in urls) {
httpListener.Prefixes.Add(url);
}
httpListener.Start();
Console.WriteLine("Http服务器开始监听端口 http://localhost:7000/ http://localhost:7001/");
while (true) {
HttpListenerContext context = httpListener.GetContext(); //阻塞,接收客户端请求
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
//返回响应正文数据
String responseString = $"<html><body><h1>Hellow,How are You?{DateTime.Now}</h1></body></html>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
//关闭输出
output.Close();
}
//服务停止监听
httpListener.Stop();
Console.WriteLine("http服务器停止监听,输入任意键退出");
Console.Read();
}
}