2014-10-02 72 views
0

我有以下HTTP偵聽器方法,很大程度上受到MSDN的HttpListener類的使用示例的啓發。我對編程相當陌生,我不知道該從哪裏去從我的Main()初始化它。有什麼建議麼?使用HttpListener

public static void HttpListener(string[] prefixes) 
    { 
     if (prefixes == null || prefixes.Length == 0) 
      throw new ArgumentException("Prefixes needed"); 

     HttpListener listener = new HttpListener(); 

     foreach (string s in prefixes) 
     { 
      listener.Prefixes.Add(s); 
     } 
     listener.Start(); 
     Console.WriteLine("Listening.."); 

     HttpListenerContext context = listener.GetContext(); 
     HttpListenerRequest request = context.Request; 
     HttpListenerResponse response = context.Response; 

     string responseString = "<HTML><BODY> Test </BODY></HTML>"; 
     byte[] buffer = Encoding.UTF8.GetBytes(responseString); 

     response.ContentLength64 = buffer.Length; 
     Stream output = response.OutputStream; 
     output.Write(buffer, 0, buffer.Length); 

     output.Close(); 
     listener.Stop(); 
    } 
+0

請解釋一下,你_want_從這裏走。 – 2014-10-02 09:23:17

+0

我的目標是能夠運行此偵聽器,然後使用Web瀏覽器發出HTTP請求,如「http:// localhost /」,或者如果它是我的網絡中的另一臺機器,那麼我的機器的IP地址。然後它應該用一個簡單的HTML頁面進行響應。 – Khaine775 2014-10-02 09:30:16

+0

你可以從你的Main()方法中調用'HttpListener(new string [] {「http:// *:80 /」});'來指定你想要處理端口80上的通信量http端口)。 – 2014-10-02 09:53:57

回答

0

你可以做這樣的事情:

public void ListenTraces() 
    { 
     httpListener.Prefixes.Add(PORT_HOST); 
     try 
     { 
      httpListener.Start(); 
     } 
     catch (HttpListenerException hlex) 
     { 
      log.Warn("Can't start the agent to listen transaction" + hlex); 
      return; 
     } 
     log.Info("Now ready to receive traces..."); 
     while (true) 
     { 
      var context = httpListener.GetContext(); // get te context 

      log.Info("New trace connexion incoming"); 
      Console.WriteLine(context.SomethingYouWant); 
     } 
    }