A simple Client and Server with HttpListener

A friend recently asked me a client and a server communicating with the least bell and whistles. After some discussion we came up with using the built in HttpListener. And here is the code

Client

static class ClientProgram
{

    static void Main()
    {
        Console.WriteLine("Client");
        //Wait for serer to start
        Thread.Sleep(1000);
        var startNew = Stopwatch.StartNew();
        var calls = 100;
        var result = Parallel.For(0, calls, CallServer);
        while (!result.IsCompleted)
        {
            Thread.Sleep(100);
        }
        startNew.Stop();
        Console.WriteLine("Client finished {0}x1sec calls in {1}sec", calls, startNew.Elapsed.Seconds);

        Console.ReadLine();

    }

    private static void CallServer(int i)
    {
        var webRequest = WebRequest.Create("http://localhost:7896/");
        webRequest.Headers["thread"] = i.ToString();
        using (var webResponse = webRequest.GetResponse())
        {
            Console.WriteLine("Client: " + webResponse.Headers["thread"]);
        }
    }
}

Server

static class ServerProgram
{
    static HttpListener listener;

    static void Main()
    {
        Console.WriteLine("Server");
        listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:7896/");
        listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;

        listener.Start();
        while (true)
        {
            ProcessRequest();
        }

    }

    static void ProcessRequest()
    {
        var startNew = Stopwatch.StartNew();
        var result = listener.BeginGetContext(ListenerCallback, listener);
        result.AsyncWaitHandle.WaitOne();
        startNew.Stop();
    }

    static void ListenerCallback(IAsyncResult result)
    {
        var context = listener.EndGetContext(result);
        Thread.Sleep(1000);
        context.Response.StatusCode = 200;
        context.Response.StatusDescription = "OK";
        var receivedText = context.Request.Headers["thread"] + " Received";
        Console.WriteLine("Server: " + receivedText);
        context.Response.Headers["thread"] = receivedText;
        context.Response.Close();
    }

}

Download the source #

The code consists of two console apps that should both be run at startup.

Working solution can be found here http://code.google.com/p/simonsexperiments/source/browse/SimpleClientServerWithHttpListener

Posted by: Simon Cropp
Last revised: 24 Dec, 2011 05:26 AM History

Comments

No comments yet. Be the first!

No new comments are allowed on this post.