简体   繁体   English

HttpListener 的使用

[英]Use of HttpListener

I have the following HTTP listener method, greatly inspired by MSDN's example use of the HttpListener class.我有以下 HTTP 侦听器方法,深受 MSDN 使用 HttpListener 类的示例的启发。 I'm fairly new to programming and I'm not sure where to go from here to initialize it from my Main().我对编程还很陌生,我不知道从哪里开始从我的 Main() 初始化它。 Any suggestions?有什么建议?

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

You seem to have removed the comments that are mentioned on the MSDN HttpListener Class page:您似乎已经删除了MSDN HttpListener Class页面上提到的注释:

// URI prefixes are required, for example " http://contoso.com:8080/index/ ". // 需要 URI 前缀,例如“ http://contoso.com:8080/index/ ”。

So just call it like that:所以就这样称呼它:

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

But please note this example will handle only one request and then exit.但请注意,此示例将仅处理一个请求,然后退出。 If your follow-up question is then "How can I make it handle multiple requests?"如果您的后续问题是“我如何让它处理多个请求?” , see Handling multiple requests with C# HttpListener . ,请参阅使用 C# HttpListener 处理多个请求

you can do something like this :你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM