我试图在C#中编写一个非常非常简单的自定义Http服务器。
.Net提供的连接代码很简单:
// get our IPv4 address
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
IPAddress theAddress = localIPs.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault();
// Create a http listener.
var listener = new HttpListener();
string myUrlPrefix = $"http://{theAddress.ToString()}:{port}/MyService/";
listener.Prefixes.Add(myUrlPrefix);
Console.WriteLine($"Trying to listen on {myUrlPrefix}");
listener.Start();
Console.WriteLine("Listening...");
HttpListenerContext context = null;
try
{
context = listener.GetContext();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
HttpListenerRequest request = context.Request;
Run Code Online (Sandbox Code Playgroud)
运行此命令时,将GetContext()阻塞,从不返回,也不会引发异常。
listener.Start() works -- the URL is properly reserved for the correct user with 'netsh http add urlacl...'., …