【问题标题】:Use of HttpListener使用 HttpListener
【发布时间】:2014-11-27 05:52:10
【问题描述】:

我有以下 HTTP 侦听器方法,很大程度上受 MSDN 使用 HttpListener 类的示例启发。我对编程相当陌生,我不确定从这里到哪里从我的 Main() 初始化它。有什么建议吗?

 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();
    }

【问题讨论】:

  • 请说明您从这里去哪里。
  • 我的目标是能够运行此侦听器,然后使用网络浏览器发出 HTTP 请求,如“localhost”,或者如果它是我网络上的另一台机器,那么我的机器的 IP 地址.然后它应该以一个简单的 HTML 页面进行响应。
  • 您可以从您的Main() 方法调用HttpListener(new string[] { "http://*:80/" });,以指定您要处理端口80(默认http 端口)上的流量。

标签: c# http


【解决方案1】:

您似乎已经删除了MSDN HttpListener Class 页面上提到的 cmets:

// URI 前缀是必需的,例如“http://contoso.com:8080/index/”。

所以就这样称呼吧:

public static void Main(string[] args)
{
    HttpListener(new[] { "http://localhost/" });
}

但请注意,此示例将只处理一个请求然后退出。如果您的后续问题是“我怎样才能让它处理多个请求?”,请参阅Handling multiple requests with C# HttpListener

【讨论】:

    【解决方案2】:

    你可以这样做:

       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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2018-05-28
      • 2013-09-21
      • 2018-11-06
      • 2013-11-12
      • 2014-09-14
      • 2012-02-09
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多