Writing an HTTP Server

You can write your own HTTP server with the HttpListener class.

The following is a simple server that listens on port 99999, waits for a single client request, and then returns a message.

HttpListener does not work on operating systems prior to Windows XP.


using System;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
class ThreadTest
{
    static void Main()
    {
        new System.Threading.Thread(Listen).Start(); // Run server in parallel. 
        Thread.Sleep (500); // Wait half a second.

        WebClient wc = new WebClient(); // Make a client request. 
        Console.WriteLine(wc.DownloadString("http://localhost:999/Request.txt"));
    }

    static void Listen()
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:999/MyApp/");  // Listen on 
        listener.Start(); // port 999

        // Wait for a client request:
        HttpListenerContext context = listener.GetContext();

        // Respond to the request:
        string msg = "You asked for: " + context.Request.RawUrl; 
        context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(msg); 
        context.Response.StatusCode = (int)HttpStatusCode.OK;

        using (Stream s = context.Response.OutputStream)
        using (StreamWriter writer = new StreamWriter(s))
            writer.Write(msg);

        listener.Stop();
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.