Click here to Skip to main content
Licence CPOL
First Posted 18 Oct 2004
Views 65,324
Downloads 3,146
Bookmarked 87 times

Building a Tiny WebServer in less than 500 lines

By Stephan Meyn | 18 Oct 2004
This tiny webserver can be hosted by applications that need to serve specialised web pages
3 votes, 17.6%
1

2
1 vote, 5.9%
3
3 votes, 17.6%
4
10 votes, 58.8%
5
4.60/5 - 17 votes
3 removed
μ 4.00, σa 2.70 [?]

Introduction

Originally I was intrigued 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.

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 App.Config file.

<appSettings>
    <add key="WebRoot" value="E:\src\DotNet\WebServer\root" />        
      <!-- location of the web pages to serve -->
    <add key="Default" value="default.html" />                        
      <!-- name of the default page -->
    <add key="TemplatePath" value="E:\src\DotNet\WebServer\html" />   
      <!-- location of special templates -->
    <add key="Port" value="81" />                                     
      <!-- Port to server on -->
    <add key="LogFile" value="" />                                    
      <!-- filepath, set to "" for console logging -->
    <add key="LogLevel" value="All" />                                
      <!--All, Warning, Error, None -->
</appSettings>
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:

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 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 suceeded 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 the RSS feeds from the sources.

The RssAggregator does two things:

  1. download and keep up to date a list of selected RSS Feeds
  2. run 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 the doGet() is pretty dumb:

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 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)

About the Author

Stephan Meyn

Web Developer

Australia Australia

Member
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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmemberktchup22:38 20 Jul '10  
QuestionTrying to use remoting on HTTPServerChannel Pinmemberaarudra5:50 3 Dec '09  
Generalneed some modification Pinmembercooldeo18t8:09 19 Jul '09  
Generalnot very secure Pinmemberinvader8212:10 25 Feb '09  
GeneralRe: not very secure PinmemberStephan Meyn10:08 26 Feb '09  
QuestionSilly Question: How to I request a page? Pinmemberflipdoubt3:01 28 Apr '07  
AnswerRe: Silly Question: How to I request a page? PinmemberGoofMan2:46 2 Oct '07  
GeneralASP.NET Runtime PinmemberdzCepheus11:51 31 Oct '04  
GeneralRe: ASP.NET Runtime PinmemberStephan Meyn11:59 31 Oct '04  
GeneralRe: ASP.NET Runtime PinmemberWallePuh22:10 5 Dec '04  
So how do you do to add support for ASP.NET in your own web server? Where can I read about this?
Generalother resources Pinmember
MadHatter ¢
21:14 25 Oct '04  
GeneralRe: other resources PinmemberStephan Meyn3:23 27 Oct '04  
GeneralRe: other resources Pinmembercooldeo18t7:43 19 Jul '09  
GeneralRe: other resources Pinmembercooldeo18t8:08 19 Jul '09  

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.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120210.1 | Last Updated 19 Oct 2004
Article Copyright 2004 by Stephan Meyn
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid