9

I have the following HTTP listener method, greatly inspired by MSDN's example use of the HttpListener class. I'm fairly new to programming and I'm not sure where to go from here to initialize it from my 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();
    }
Khaine775
  • 2,715
  • 8
  • 22
  • 51
  • 1
    Please explain where you _want_ to go from here. – C.Evenhuis Oct 02 '14 at 09:23
  • My goal is to be able to run this listener, and then use a web browser to make a HTTP request like "http://localhost/" or if it's another machine on my network, then my machine's IP address. It should then respond with a simple HTML page. – Khaine775 Oct 02 '14 at 09:30
  • 1
    You'd call `HttpListener(new string[] { "http://*:80/" });` from your `Main()` method, to specify that you want to handle traffic on port 80 (the default http port). – C.Evenhuis Oct 02 '14 at 09:53

2 Answers2

15

You seem to have removed the comments that are mentioned on the MSDN HttpListener Class page:

// URI prefixes are required, for example "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.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
3

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);
        }
    }
SarahB
  • 135
  • 1
  • 11