2017-06-17 144 views
0

我有一些問題,創建使用HttpListener一個本地網絡服務器。當我使用localhost uri(或127.0.0.1)時,它工作得很好,很好地響應請求。C#HttpListener沒有響應

然而,當我加入一些madeup域名,如「whateverabc.com」,服務器沒有響應請求再和鉻是印刷ERR_NAME_NOT_RESOLVED錯誤。

我缺少什麼?謝謝!

public class WebServer 
{ 
    private readonly HttpListener _listener = new HttpListener(); 
    private readonly Func<HttpListenerRequest, string> _responderMethod; 

    public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method) 
    {    
     if (!HttpListener.IsSupported) 
      throw new NotSupportedException(
       "Needs Windows XP SP2, Server 2003 or later."); 

     if (prefixes == null || prefixes.Length == 0) 
      throw new ArgumentException("prefixes"); 

     if (method == null) 
      throw new ArgumentException("method"); 

     foreach (string s in prefixes) 
      _listener.Prefixes.Add(s); 

     _listener.IgnoreWriteExceptions = true; 
     _responderMethod = method; 
     _listener.Start(); 
    } 

    public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes) 
     : this(prefixes, method) { } 

    public void Run() 
    { 
     ThreadPool.QueueUserWorkItem((o) => 
     { 
      Console.WriteLine("Webserver running..."); 
      try 
      { 
       while (_listener.IsListening) 
       { 
        ThreadPool.QueueUserWorkItem((c) => 
        { 
         var ctx = c as HttpListenerContext; 
         try 
         { 
          string rstr = _responderMethod(ctx.Request); 
          byte[] buf = Encoding.UTF8.GetBytes(rstr); 
          ctx.Response.ContentLength64 = buf.Length; 
          ctx.Response.OutputStream.Write(buf, 0, buf.Length); 
         } 
         catch { } // suppress any exceptions 
         finally 
         { 
          ctx.Response.OutputStream.Close(); 
         } 
        }, _listener.GetContext()); 
       } 
      } 
      catch { } // suppress any exceptions 
     }); 
    } 

    public void Stop() 
    { 
     _listener.Stop(); 
     _listener.Close(); 
    } 
} 

static void Main(string[] args) 
    { 
     WebServer ws = new WebServer(SendResponse, "http://whateverabc.com:54785/"); 
     ws.Run(); 
     Console.WriteLine("A simple webserver. Press a key to quit."); 
     Console.ReadKey(); 
     ws.Stop(); 
    } 

    public static string SendResponse(HttpListenerRequest request) 
    { 
     return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now); 
    } 

回答

0

這似乎有一個根本性的誤解。事情是這樣的:

通過註冊一個前綴,你只要告訴你的服務器來服務於與前綴開頭,並跳轉到指定端口的請求。

但是,當您使用Chrome瀏覽器(或其他任何網頁)訪問您的網站時,首先會向配置的DNS服務器發送DNS請求,以查找「whateverabc.com」域指向哪個IP地址。而且,由於該地址根本不存在(可以檢查https://www.whois.com/)您的請求失敗。所以你的網絡服務器沒有收到開始的請求。

想想這樣(或者試試看):如果你要在本地機器上啓動一個網絡服務器,並讓它監聽以「http://www.microsoft.com」開頭的請求,你真的希望你的Chrome來電訪問當您在Microsoft網站中輸入時,您的本地網絡服務器?