HttpListener仅处理对本地主机的请求

时间:2020-08-11 08:17:40

标签: c# .net httplistener

我正在基于doc测试HttpListener。我的代码很简单。这是一个以admin特权运行的控制台应用程序:

[STAThread]
static void Main( string[] args )
{
    var prefixes = new[] { "http://localhost:8080/", "http://www.contoso.com:8080/index/" };
    HttpListener listener = new HttpListener();
    foreach( string s in prefixes )
    {
        listener.Prefixes.Add( s );
    }
    listener.Start();
    IAsyncResult result = listener.BeginGetContext( new AsyncCallback( ListenerCallback ), listener );
    Console.WriteLine( "Waiting for request to be processed asyncronously." );
    result.AsyncWaitHandle.WaitOne();
    Console.WriteLine( "Request processed asyncronously." );
    Console.ReadLine();
    listener.Close();
}

public static void ListenerCallback( IAsyncResult result )
{
    HttpListener listener = (HttpListener)result.AsyncState;
    HttpListenerContext context = listener.EndGetContext( result );
    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;
    System.IO.Stream output = response.OutputStream;
    output.Write( buffer, 0, buffer.Length );
    output.Close();
 }

如果我在网络浏览器中尝试http://localhost:8080/,则会调用回调ListenerCallback,并且响应字符串“ Hello world!”。出现在浏览器中。

对于http://www.contoso.com:8080/index/,永不调用该回调,并且Web请求超时。 如何确定问题出在哪里?是.NET框架还是我的代码中的错误?

0 个答案:

没有答案