HttpListener Continued

As promised, below is a short example of how to use the HttpListener class. After you have started the sample server below, open your web browser and load the URL http://blog.mikehacker.net:8080. You should see the words "Hello World". Try http://blog.mikehacker.net:8080/date to see the current date or http://blog.mikehacker.net:8080/time to see the current time. Very cool eh?

You may need to remove some of the line wraps when you copy the code to VS.NET.

Code:

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

namespace httplistenertest

{

class Program

{

static void Main(string[] args)

{

HttpListener listener = new HttpListener();

listener.Prefixes.Add("http://blog.mikehacker.net:8080/");

listener.Start();

 

IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListnerCallback), listener);

Console.WriteLine("Waiting for request");

 

while (true) { }

 

listener.Close();

Console.WriteLine("done");

Console.ReadLine();

}

 

public static void ListnerCallback(IAsyncResult result)

{

HttpListener listener = (HttpListener)result.AsyncState;

HttpListenerContext context = listener.EndGetContext(result);

HttpListenerRequest request = context.Request;

HttpListenerResponse response = context.Response;

 

string responseString="";

switch (request.Url.AbsolutePath)

{

case "/time":

responseString = "<html><body>The current time is: " + DateTime.Now.ToLongTimeString() + "</body></html>";

break;

 

case "/date":

responseString = "<html><body>The current date is: " + DateTime.Now.ToLongDateString() + "</body></html>";

break;

 

 

default:

responseString = "<html><body>Hello World!";

break;

}

 

 

byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

response.ContentLength64 = buffer.Length;

System.IO.Stream output = response.OutputStream;

output.Write(buffer, 0, buffer.Length);

output.Close();

 

listener.BeginGetContext(new AsyncCallback(ListnerCallback), listener);

}

 

}

}

 

Sorry about the code formatting, some reason it was messed up during the publishing of this entry.

 

Leave a Reply