2014-10-02 24 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); 
     } 
    }