Click here to Skip to main content
11,930,788 members (50,463 online)
Click here to Skip to main content
Add your own
alternative version


61 bookmarked

C# Customizable Embedded HTTPServer

, 14 Nov 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
A customizable embedded HTTPServer for C#.

Screenshot - screenshot2.jpg


This article describes the usage of a small HTTP server library entirely written in C# that can be integrated and used in your own application. The purpose of this library is to provide developers with an easy to use and flexible way of generating HTTP responses on the fly based on the requested URI and/or the current state of the application.


This library was developed by Hybrid GeoTools to act as an integrated web server to provide dynamic data to Google Earth. Although handling Google Earth's requests is a simple task at a first glance, it became apparent that not handling the HTTP protocol properly can cause unexpected results. For instance, not handling the Connect header properly caused Google Earth to reuse the connection while the server was actually waiting for a new connection. As a result, the request was not handled at all.

For this reason, the HybridDSP.Net library was developed. Currently, this library only contains the HTTPServer, but more services might be added in the future.


The library exposes four classes and two interfaces:

  • HTTPServer - This class is the actual server. It manages the connections, the sessions, and the requests. It delegates the handling of a request to a request handler object that conforms to the IHTTPRequestHandler interface. This object is obtained through a request handler factory that's passed as one of the arguments of the contractor for HTTPServer. This factory has to conform to the IHTTPRequestHandlerFactory interface.
  • HTTPServerRequest - This class represents a request from a client to the server. The request handler factory can instantiate a request handler based on information obtained from the request. Once a request handler has been instantiated, it will be used to handle the request. If the request contains any data, a Stream can be obtained from the request to get the data (and do whatever needs to be done with it).
  • HTTPServerResponse - This class represents the response from the server to the client. It's initialized to return HTTP OK, by default. Once all headers are set correctly, a Stream can be obtained by sending the header to the client. The body of the response can be written to this Stream.
  • IHTTPRequestHandler - This interface defines the contract to which any request handler needs to conform. There's only one method defined:
  • public interface IHTTPRequestHandler
        void HandleRequest(HTTPServerRequest request, HTTPServerResponse response);
  • IHTTPRequestHandlerFactory - This interface defines the contract to which any request handler factory needs to conform. Again, there's only one method defined:
  • public interface IHTTPRequestHandlerFactory
        IHTTPRequestHandler CreateRequestHandler(HTTPServerRequest request);

Using the code

First of all, at least one request handler needs to be defined in order to be able to do anything.

class DateTimeHandler : IHTTPRequestHandler
    public void HandleRequest(HTTPServerRequest request, HTTPServerResponse response)
        if (request.URI == "/")
             * In this example we'll write the body into the
             * stream obtained by response.Send(). This will cause the
             * KeepAlive to be false since the size of the body is not
             * known when the response header is sent.
            response.ContentType = "text/html";
            using (Stream ostr = response.Send())
            using (TextWriter tw = new StreamWriter(ostr))
                tw.WriteLine("<title>Date Time Server</title>");
                tw.WriteLine("<meta http-equiv=\"refresh\" content=\"2\">");
            response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_NOT_FOUND;

This handler will generate an HTML page that shows the current date and time and refreshes itself every two seconds. If the request is not for the root, it will return an HTTP NOT FOUND response.

Next, a request handler factory needs to be defined in order to use the just created request handler.

class RequestHandlerFactory : IHTTPRequestHandlerFactory
    public IHTTPRequestHandler CreateRequestHandler(HTTPServerRequest request)
        return new DateTimeHandler();

This factory will simply always instantiate a DateTimeHandler.

The last step is to hook the whole thing together. To do this one has to instantiate a factory and pass it to the contructor of the HTTPServer object. Then the server can simply be started.

static void Main(string[] args)
    RequestHandlerFactory factory = new RequestHandlerFactory();
    HTTPServer server = new HTTPServer(factory, 8080);

    Console.Write("Press enter to abort.");


Now, take your favorite web browser, browse to http://localhost:8080, and enjoy your very own integrated web server.


  • 12 September 2007 - Initial issue.
  • 13 September 2007 - Updated the screenshot.
  • 14 November 2007 - Added support for IPv6.
  • 15 November 2007 - Fixed issue in killing the server thread.


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


About the Author

You may also be interested in...

Comments and Discussions

QuestionResponse.SendFile error Pin
kubibay23-Mar-15 23:22
memberkubibay23-Mar-15 23:22 
QuestionSlow response from server Pin
JoshuaHebbel23-Jul-14 8:40
memberJoshuaHebbel23-Jul-14 8:40 
Questionwhy localhost works,but can't? Pin
Xiqiang Sun23-Jun-13 23:32
memberXiqiang Sun23-Jun-13 23:32 
QuestionSuggestion for IPv6 implementation Pin
Grismar6-Jan-13 6:54
memberGrismar6-Jan-13 6:54 
Hi there, nice work on writing the server, I plan on using it in a media player plugin, to expose its (.Net) API as a JSON interface. Working beautifully and with a few modifications to your ServerRequest and ServerResponse, I was also able to use cookies for some simple application session management. So thanks Smile | :) .

One suggestion: I noticed that the server decides whether to bind to IPv6 or IPv4 based on whether IPv6 is supported. However, when it binds to IPv6, it no longer accepts connections on IPv4 URLs (like or any other). This can be easily fixed by changing the following to the end of the HTTPServer constructor:

_socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
if (addressFamily == AddressFamily.InterNetworkV6) 
    // Tell the socket to accept both IPv6 and IPv4
    _socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);
_socket.Bind(new IPEndPoint(bindAddress, port));

I've changed this for my own purposes, but perhaps you might consider updating your version as well, unless you know of drawbacks I am missing?

At the very least, I'd want to make it an option, instead of simply not supporting IPv4 on IPv6 systems.

Thanks again,
Jaap van der Velde.
QuestionAs for video stream content, any idea how to send in chunks? Pin
seanzcan18-Sep-12 11:44
memberseanzcan18-Sep-12 11:44 
AnswerRe: As for video stream content, any idea how to send in chunks? Pin
Mark Swaanenburg19-Sep-12 21:17
memberMark Swaanenburg19-Sep-12 21:17 
GeneralRe: As for video stream content, any idea how to send in chunks? Pin
seanzcan20-Sep-12 5:40
memberseanzcan20-Sep-12 5:40 
GeneralRe: As for video stream content, any idea how to send in chunks? Pin
kubibay23-Mar-15 23:12
memberkubibay23-Mar-15 23:12 
QuestionWhere is the http server folder or how do I specify the server default folder/location? Pin
seanzcan13-Aug-12 12:04
memberseanzcan13-Aug-12 12:04 
AnswerRe: Where is the http server folder or how do I specify the server default folder/location? Pin
Mark Swaanenburg13-Aug-12 23:33
memberMark Swaanenburg13-Aug-12 23:33 
GeneralRe: Where is the http server folder or how do I specify the server default folder/location? Pin
seanzcan14-Aug-12 4:47
memberseanzcan14-Aug-12 4:47 
QuestionWindows Seven Compatibility Pin
kri251211-Jul-11 6:34
memberkri251211-Jul-11 6:34 
AnswerRe: Windows Seven Compatibility Pin
Mark Swaanenburg11-Jul-11 7:52
memberMark Swaanenburg11-Jul-11 7:52 
GeneralRe: Windows Seven Compatibility Pin
Grismar6-Jan-13 9:28
memberGrismar6-Jan-13 9:28 
AnswerRe: Windows Seven Compatibility Pin
soho11-Jan-12 6:09
membersoho11-Jan-12 6:09 
QuestionCan't handle multiple simultaneous requests? Pin
dbassett742-Dec-09 7:51
memberdbassett742-Dec-09 7:51 
AnswerRe: Can't handle multiple simultaneous requests? Pin
Mark Swaanenburg2-Dec-09 8:19
memberMark Swaanenburg2-Dec-09 8:19 
GeneralSimple clear practical Pin
Wayne Walter31-Aug-09 21:43
memberWayne Walter31-Aug-09 21:43 
AnswerRe: Simple clear practical Pin
Mark Swaanenburg31-Aug-09 21:58
memberMark Swaanenburg31-Aug-09 21:58 
GeneralQuestion on IO Pin
Jim Crafton14-Nov-07 5:04
memberJim Crafton14-Nov-07 5:04 
GeneralRe: Question on IO Pin
Mark Swaanenburg14-Nov-07 5:16
memberMark Swaanenburg14-Nov-07 5:16 
QuestionIPv6 problems Pin
Dorli13-Nov-07 6:45
memberDorli13-Nov-07 6:45 
AnswerRe: IPv6 problems Pin
Mark Swaanenburg14-Nov-07 1:06
memberMark Swaanenburg14-Nov-07 1:06 
QuestionWhy didn't you use the HttpListener Class Pin
GLLNS12-Sep-07 4:14
memberGLLNS12-Sep-07 4:14 
AnswerRe: Why didn't you use the HttpListener Class Pin
Mark Swaanenburg12-Sep-07 4:33
memberMark Swaanenburg12-Sep-07 4:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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
Web04 | 2.8.151126.1 | Last Updated 14 Nov 2007
Article Copyright 2007 by Mark Swaanenburg
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid