Click here to Skip to main content
Click here to Skip to main content

Simple HTTP Server in C#

, 23 Mar 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Threaded synchronous HTTP Server abstract class, to respond to HTTP requests


This article covers a simple HTTP server class which you may incorporate into your own projects, or review to learn more about the HTTP protocol.


High performance web services are often hosted in rock solid webservices like IIS, Apache, or Tomcat. However, HTML is such a flexible UI language, that it can be useful to serve an HTML UI out of practically any application or backend server. In these situations, the overhead and configuration complexity of an external webserver is seldom worth the trouble. What's needed is a simple HTTP class which can be easily embedded to service simple web requests. This class meets that need.

Using the Code

First let's review how to use the class, and then we'll dig into some of the details of how it operates. We begin by subclassing HttpServer and providing implementations for the two abstract methods handleGETRequest and handlePOSTRequest...

public class MyHttpServer : HttpServer {
    public MyHttpServer(int port)
        : base(port) {
    public override void handleGETRequest(HttpProcessor p) {
        Console.WriteLine("request: {0}", p.http_url);
        p.outputStream.WriteLine("<html><body><h1>test server</h1>");
        p.outputStream.WriteLine("Current Time: " + DateTime.Now.ToString());
        p.outputStream.WriteLine("url : {0}", p.http_url);
        p.outputStream.WriteLine("<form method=post action=/form>");
        p.outputStream.WriteLine("<input type=text name=foo value=foovalue>");
        p.outputStream.WriteLine("<input type=submit name=bar value=barvalue>");
    public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData) {
        Console.WriteLine("POST request: {0}", p.http_url);
        string data = inputData.ReadToEnd();
        p.outputStream.WriteLine("<html><body><h1>test server</h1>");
        p.outputStream.WriteLine("<a href=/test>return</a><p>");
        p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data);

Once a simple request processor is provided, one must instantiate the server on a port, and start a thread for the main server listener.

 HttpServer httpServer = new MyHttpServer(8080);
 Thread thread = new Thread(new ThreadStart(httpServer.listen));

If you compile and run the sample project, you should be able to point a web-browser of choice at http://localhost:8080 to see the above simple HTML pages rendered. Let's take a brief look at what's going on under the hood.

This simple webserver is broken into two components. The HttpServer class opens a TcpListener on the incoming port, and sits in a loop handling incoming TCP connect requests using AcceptTcpClient(). This is the first step of handling an incoming TCP connection. The incoming request arrived on our "well known port", and this accept process creates a fresh port-pair for server to communicate with this client on. That fresh port-pair is our TcpClient session. This keeps our main accept port free to accept new connections. As you can see in the code below, each time the listener returns a new TcpClient, HttpServer creates a new HttpProcessor and starts a new thread for it to operate in. This class also contains the abstract methods our subclass must implement in order to produce a response.

public abstract class HttpServer {

    protected int port;
    TcpListener listener;
    bool is_active = true;
    public HttpServer(int port) {
        this.port = port;
    public void listen() {
        listener = new TcpListener(port);
        while (is_active) {                
            TcpClient s = listener.AcceptTcpClient();
            HttpProcessor processor = new HttpProcessor(s, this);
            Thread thread = new Thread(new ThreadStart(processor.process));
    public abstract void handleGETRequest(HttpProcessor p);
    public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData);

At this point, the new client-server TCP connection is handed off to the HttpProcessor in its own thread. The HttpProcessor's job is to properly parse the HTTP headers, and hand control to the proper abstract method handler implementation. Let's look at just a few small parts of the HTTP header processing. The first line of an HTTP Request resembles the following:

GET /myurl HTTP/1.0 

After setting up the input and output stream in process(), our HttpProcessor calls parseRequest(), where the above HTTP request line is received and parsed.

public void parseRequest() {
    String request = inputStream.ReadLine();
    string[] tokens = request.Split(' ');
    if (tokens.Length != 3) {
        throw new Exception("invalid http request line");
    http_method = tokens[0].ToUpper();
    http_url = tokens[1];
    http_protocol_versionstring = tokens[2];

    Console.WriteLine("starting: " + request);

The HTTP request line is always three parts, so we simply use a string.Split() call to separate it into three pieces. The next step is to receive and parse the HTTP headers from the client. Each header-line includes a type of the form KEY:Value. An empty line signifies the end of the HTTP headers. Our code to readHeaders is the following:

public void readHeaders() {
    String line;
    while ((line = inputStream.ReadLine()) != null) {
        if (line.Equals("")) {
            Console.WriteLine("got headers");
        int separator = line.IndexOf(':');
        if (separator == -1) {
            throw new Exception("invalid http header line: " + line);
        String name = line.Substring(0, separator);
        int pos = separator + 1;
        while ((pos < line.Length) && (line[pos] == ' ')) {
            pos++; // strip any spaces
        string value = line.Substring(pos, line.Length - pos);
        Console.WriteLine("header: {0}:{1}",name,value);
        httpHeaders[name] = value;

For each line, we look for the colon (Smile | :) separator, grabbing the string before as a name, and the string after as a value. When we reach an empty header-line, we return because we have received all headers.

At this point, we know enough to handle our simple GET or POST, so we dispatch to the proper handler. In the case of a post, there is some trickiness to deal with in accepting the post data. One of the request headers includes the content-length of the post data. While we wish to let our subclass's handlePOSTRequest actually deal with the post data, we need to only allow them to request content-length bytes off the stream, otherwise they will be stuck blocking on the input stream waiting for data which will never arrive. In this simple server, we handle this situation with the dirty but effective strategy of reading all the post data into a MemoryStream before sending this data to the POST handler. This is not ideal for a number of reasons. First, the post data may be large. In fact it may be a file upload, in which case buffering it into memory may not be efficient or even possible. Ideally, we would create some type of stream-imitator that could be setup to limit itself to content-length bytes, but otherwise act as a normal stream. This would allow the POST handler to pull data directly off the stream without the overhead of buffering in memory. However, this is also much more code. In many embedded HTTP servers, post requests are not necessary at all, so we avoid this situation by simply limiting POST input data to no more than 10MB.

Another simplification of this simple server is the content-type of the return data. In the HTTP protocol, the server always sends the browser the MIME-Type of the data which it should be expecting. In writeSuccess(), you can see that this server always indicates a content-type of text/html. If you wish to return other content types, you will need to extend this method to allow your handler to supply a content type response before it sends data to the client.

Points of Interest

This SimpleHttpServer only implements a very bare-bones subset of even the basic HTTP/1.0 spec. Further revisions of the HTTP specification have included more complex and very valuable improvements, including compression, session keep alive, chunked responses, and lots more. However, because of the excellent and simple design of HTTP, you'll find that even this very bare-bones code is capable of serving pages which are compatible with modern web-browsers.

Other similar embeddable servers include:


  • December 19, 2010: Initial version posted
  • December 22, 2010: Removed StreamReader from input side so we can properly get raw POST data 
  • March 2, 2012: corrected line-terminators to use WriteLine() for \r\n instead of just \n 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

David Jeske

United States United States
David Jeske is an Entrepreneur and Computer Programmer, currently living in San Francisco, California.
He earned his B.S. Computer Engineering at University of Illnois at Champaign/Urbana (UIUC), and has worked at several Silicon Valley companies, including Google, Yahoo,, 3dfx, and Akklaim Entertainment. He has managed and architected extremely high-traffic websites, including Yahoo Groups and, and has experience in a broad spectrum of technology areas including scalability, databases, drivers, system software, and 3d graphics.
You can contact him at davidj -a-t- gmail (dot) com for personal messages about this article.

Comments and Discussions

QuestionSTOP and START the server Pinmemberchienlim18-Apr-12 23:41 
QuestionHttpWebRequest "POST" return error message Pinmemberchienlim23-Mar-12 13:49 
AnswerRe: HttpWebRequest "POST" return error message PinmemberDavid Jeske23-Mar-12 21:15 
GeneralRe: HttpWebRequest "POST" return error message PinmemberABurkard26-Mar-12 12:08 
GeneralRe: HttpWebRequest "POST" return error message Pinmemberchienlim29-Mar-12 16:03 
GeneralRe: HttpWebRequest "POST" return error message PinmemberDavid Jeske23-Mar-13 18:13 
QuestionImage Handling Pinmemberd4v1dza22-Jan-12 8:12 
AnswerRe: Image Handling PinmemberDavid Jeske1-Mar-12 14:20 
GeneralRe: Image Handling Pinmemberd4v1dza1-Mar-12 21:56 
GeneralRe: Image Handling PinmemberDavid Jeske2-Mar-12 7:36 
GeneralRe: Image Handling PinmemberGeno Carman20-Jul-12 6:09 
GeneralRe: Image Handling PinmemberDavid Jeske20-Jul-12 10:39 
GeneralRe: Image Handling [modified] PinmemberGeno Carman21-Jul-12 8:37 
GeneralRe: Image Handling PinmemberDavid Jeske21-Jul-12 11:14 
This line is invalid..
This line above will corrupt binary data because it tries to decode into utf8. You need to use the other code I supplied, which outputs the byte[] directly into the stream.
If you still have trouble, I recommend you make a test client which uses an http client fetch to grab the image itself directly. This will allow you to look at the actual bytes your server is sending for the image url.. to debug why it isn't coming back correctly. You can also try using a telnet client to manually request your image url.. to see what the server is returning.
When I get a chance ill post a working code snippets for images so you can either use it or compare it to your code and see what you might be doing wrong.
GeneralRe: Image Handling PinmemberGeno Carman21-Jul-12 11:16 
GeneralRe: Image Handling [modified] PinmemberDavid Jeske21-Jul-12 12:05 
GeneralRe: Image Handling PinmemberDavid Jeske21-Jul-12 12:29 
GeneralRe: Image Handling PinmemberGeno Carman21-Jul-12 14:28 
GeneralRe: Image Handling PinmemberMember 903762619-Aug-13 0:46 
GeneralRe: Image Handling PinmemberDavid Jeske19-Aug-13 7:37 
GeneralRe: Image Handling PinmemberMember 903762620-Aug-13 21:08 
QuestionDoes this run in IIS? PinmemberTimmins11-Dec-11 9:40 
AnswerRe: Does this run in IIS? PinmemberDavid Jeske11-Dec-11 16:12 
SuggestionAdding Basic Authentication [modified] PinmemberMember 838865625-Nov-11 14:41 
GeneralMy vote of 5 PinmemberMember 838865625-Nov-11 14:15 
GeneralOriginal code was at Pinmemberntorrisi14-Jun-11 5:14 
GeneralRe: Original code was at [modified] [modified] PinmemberDavid Jeske14-Jun-11 23:16 
GeneralThere is a error here. Pinmemberlls112728-Feb-11 18:11 
GeneralRe: There is a error here. PinmemberDavid Jeske2-Mar-12 7:57 
Generalredirect Pinmemberthomasholme7-Jan-11 13:36 
GeneralRe: redirect PinmemberByJG18-Feb-11 7:40 
GeneralMy vote of 4 PinmemberJay R. Wren1-Jan-11 6:12 
AnswerRe: My vote of 4 PinmemberByJG18-Feb-11 8:32 
GeneralRe: My vote of 4 PinmemberByJG18-Feb-11 9:05 
GeneralMy vote of 5 Pinmemberarhoads7627-Dec-10 3:15 
GeneralNice code and a small problem PinmemberSkymir21-Dec-10 4:12 
GeneralRe: Nice code and a small problem PinmemberDavid Jeske21-Dec-10 9:41 
GeneralRe: Nice code and a small problem PinmemberSkymir22-Dec-10 3:50 
GeneralRe: Nice code and a small problem PinmemberDavid Jeske22-Dec-10 9:01 
GeneralRe: Nice code and a small problem PinmemberSkymir22-Dec-10 10:30 
GeneralMy vote of 5 Pinmembersam.hill20-Dec-10 9:08 
GeneralUseful bit of code PinmemberTom Nielsen20-Dec-10 8:34 
GeneralAlternatives PinmemberNicolas Penin20-Dec-10 4:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150326.1 | Last Updated 24 Mar 2013
Article Copyright 2010 by David Jeske
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid