Click here to Skip to main content
15,860,861 members
Articles / Web Development / HTML

Building a Tiny WebServer in Less than 500 Lines

Rate me:
Please Sign up or sign in to vote.
4.88/5 (35 votes)
23 Aug 2013CPOL3 min read 129.6K   6K   152   37
This tiny webserver can be hosted by applications that need to serve specialised web pages.

Introduction

Originally, I was intrigued with what it would take to write a simple webserver. But as I progressed, I realized that a tiny web server could be quite useful for a number of applications that need to serve specialized web pages and where the overhead of writing an ASP.NET application is not warranted (or where it is not possible to host ASP.NET).

A good example is a news aggregator, which serves a single page containing the current news feeds. This is included as an example in this project.

Update (July 2013): As has been requested, I added handling of the POST command.

Using the Code

The core of the application is the class TinyServer. This class provides a simple web server that only supports GET requests (no forms) and serves web pages from a directory.

To run the sample webserver, you need to build the WebServer project and configure its settings:.

WebRoot     : "E:\src\DotNet\WebServer\root"    <!-- location of the web pages to serve -->
DefaultPage :"default.html"                     <!-- name of the default page -->
TemplatePath: "E:\src\DotNet\WebServer\html"    <!-- location of special templates -->
Port        : 81"                               <!-- Port to server on -->
LogFile     : ""                                <!-- filepath, set to "" for console logging -->
LogLevel    : "All"                             <!--All, Warning, Error, None -->

Once the WebServer application starts, it instantiates TinyServer and calls Run(). This spins off the server in a separate thread. Calling Stop() terminates the thread.

Building Your Own WebServer

Most likely, you would want to build your own version of this webserver. You need to subclass TinyServer and then override the necessary functions. The most important to override is the method doGet(). In this method, you can interrogate the GET command and send back anything that is necessary.

This is the default implementation to handle a GET command:

C#
protected virtual void doGet(string argument)
{
  string url = getUrl(argument);
  if (url.StartsWith("/"))
    url = url.Substring(1);
  if (url.Length == 0)
    url = defaultPageName;
    
  string path = Path.Combine(webRootPath, url);
  if (File.Exists(path))
  {
    sendOk();
    sendfile(path);
  }
  else
    sendError(404, "File Not Found");
}

To handle a POST command, there is a doPost function that you can override. Currently, it does very little:

C#
protected virtual void doPost(string argument, string Content)
{
   log(LogKind.Informational, "Post Data: '{0}'", Content);
   sendOk(); 
}

As you can see, the content of the post is available as a string.

To implement your version, there are a number of utility functions at hand:

  • string getUrl(string argument) takes the command parameter of doGet and extracts the URL
  • string [] urlArgs returns a list of arguments that succeeded the URL
  • sendOK() sends the OK header; this is necessary before you send any HTML
  • sendError(int errornr, string errorMsg) sends an error instead of the OK
  • sendString(string) sends a message
  • sendFile(path) sends a whole file
  • sendTemplate (templateName) sends a file in the template directory

The RssAggregator Sample Application

To demonstrate this ability, I have written a simple news aggregator that regularly downloads RSS feeds from the sources.

The RssAggregator does two things:

  1. Downloads and keeps up to date a list of selected RSS feeds
  2. Runs a web server that returns a web page containing the feed detail

The first part uses the RssReader class created by smallguy78. It runs in its own thread and will download feeds once the current copy is older than one hour.

The second part is implemented by a subclass of TinyServer called AggServer. AggServer only ever returns one page that contains the newsfeeds abstracts and links to the articles. So doGet() is pretty dumb:

C#
protected override void doGet(string argument)
{
  this.sendOk();
  this.sendString(writeLinkPage());
}

The smarts to create the webpage is in the method writeLinkPage() which in turn relies on the helper function RssReader.CreateHtml(). The whole example (excluding RssReader) just takes 80 lines of code.

Points of Interest

Acknowledgements to smallguy78 whose RssReader code I used. You can find more about it in this RSS Reader article.

License

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


Written By
Web Developer
Australia Australia
I am a Software Engineer/Consultant. My work is focussed on helping teams to get more out of their work. So I teach how to do requirements, analysis and design in a format that is easy to understand and apply.
I help with testing too, from starting developers on automated unit testing to running whole testing teams and how they cooperate with development.

For really big projects I provide complete methodologies that support all of the lifecycle.

For relaxation I paddle a sea kayak around Sydney and the Central Coast or write utilities on rainy days to make my life easier.

Comments and Discussions

 
QuestionMissing code Pin
TheGreatAndPowerfulOz8-Aug-18 6:17
TheGreatAndPowerfulOz8-Aug-18 6:17 
Questionwell guessed series of ..\..\..\C:\users in the GET Request Pin
Ravichanadeepakarandescarar8-Aug-16 16:18
Ravichanadeepakarandescarar8-Aug-16 16:18 
Questionfurther code improvements Pin
rj2Skipper4-Sep-14 21:53
rj2Skipper4-Sep-14 21:53 
GeneralMy vote of 5 Pin
Volynsky Alex23-Aug-13 23:29
professionalVolynsky Alex23-Aug-13 23:29 
GeneralMy vote of 5 Pin
descartes25-Jul-13 7:40
descartes25-Jul-13 7:40 
GeneralMy vote of 5 Pin
Bassam Abdul-Baki25-Jul-13 4:22
professionalBassam Abdul-Baki25-Jul-13 4:22 
GeneralMy vote of 5 Pin
nobodyxxxxx25-Jul-13 3:56
nobodyxxxxx25-Jul-13 3:56 
QuestionI can't download de source Pin
descartes25-Jul-13 2:48
descartes25-Jul-13 2:48 
AnswerRe: I can't download de source Pin
Stephan Meyn25-Jul-13 3:20
Stephan Meyn25-Jul-13 3:20 
GeneralRe: I can't download de source Pin
descartes25-Jul-13 3:42
descartes25-Jul-13 3:42 
GeneralRe: I can't download de source Pin
Stephan Meyn25-Jul-13 4:35
Stephan Meyn25-Jul-13 4:35 
QuestiondoPost() Pin
arschdepp24-Jul-13 0:46
arschdepp24-Jul-13 0:46 
AnswerRe: doPost() Pin
Stephan Meyn25-Jul-13 0:39
Stephan Meyn25-Jul-13 0:39 
GeneralRe: doPost() Pin
arschdepp25-Jul-13 1:00
arschdepp25-Jul-13 1:00 
GeneralRe: doPost() Pin
Stephan Meyn25-Jul-13 1:23
Stephan Meyn25-Jul-13 1:23 
GeneralRe: doPost() Pin
arschdepp25-Jul-13 1:41
arschdepp25-Jul-13 1:41 
GeneralRe: doPost() Pin
Stephan Meyn25-Jul-13 2:12
Stephan Meyn25-Jul-13 2:12 
GeneralRe: doPost() Pin
arschdepp25-Jul-13 3:05
arschdepp25-Jul-13 3:05 
GeneralRe: doPost() Pin
Stephan Meyn25-Jul-13 3:21
Stephan Meyn25-Jul-13 3:21 
GeneralRe: doPost() Pin
Stephan Meyn25-Jul-13 4:36
Stephan Meyn25-Jul-13 4:36 
GeneralRe: doPost() Pin
arschdepp25-Jul-13 23:08
arschdepp25-Jul-13 23:08 
GeneralMy vote of 5 Pin
Gun Gun Febrianza12-Oct-12 16:10
Gun Gun Febrianza12-Oct-12 16:10 
GeneralMy vote of 5 Pin
Victor Barbu31-Aug-12 5:05
Victor Barbu31-Aug-12 5:05 
GeneralMy vote of 5 Pin
Julien LEVESQUE20-Jul-10 21:38
Julien LEVESQUE20-Jul-10 21:38 
QuestionTrying to use remoting on HTTPServerChannel Pin
aarudra3-Dec-09 4:50
aarudra3-Dec-09 4:50 

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.