Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 27,763 times

Contents

Downloads

Related Categories

Create your own Web Server using C# - The Code

Imtiaz Alam

The Code

Let us dive into the code...

// MyWebServer Written by Imtiaz Alam
namespace Imtiaz 
{

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading ;

class MyWebServer 
{

    private TcpListener myListener ;
    private int port = 5050 ;  // Select any free port you wish 
    //The constructor which make the TcpListener start listening on the
    //given port. It also calls a Thread on the method StartListen(). 

    public MyWebServer()
    {
        try
        {
            //start listing on the given port
            myListener = new TcpListener(port) ;
            myListener.Start();
            Console.WriteLine("Web Server Running... Press ^C to Stop...");
            
            //start the thread which calls the method 'StartListen'
            Thread th = new Thread(new ThreadStart(StartListen));
            th.Start() ;

        }
        catch(Exception e)
        {
            Console.WriteLine("An Exception Occurred while Listening :" +e.ToString());
        }
    }

We defined namespace, included the references required in our application and initialized the port in the constructor, started the listener and created a new thread and called startlisten function.

Now let us assume that the user does not supplies the file name, in that case we have to identify the default filename and send to the browser, as in IIS we define the default document under documents tab.

We have already stored the default file name in the default.dat and stored in the data directory. The GetTheDefaultFileName function takes the directory path as input, open the default.dat file and looks for the file in the directory provided and returns the file name or blank depends on the situation.

public string GetTheDefaultFileName(string sLocalDirectory)
{
    StreamReader sr;
    String sLine = "";

    try
    {
        //Open the default.dat to find out the list
        // of default file
        sr = new StreamReader("data\\Default.Dat");

        while ((sLine = sr.ReadLine()) != null)
        {
            //Look for the default file in the web server root folder
            if (File.Exists( sLocalDirectory + sLine) == true)
                break;
        }
    }
    catch(Exception e)
    {
        Console.WriteLine("An Exception Occurred : " + e.ToString());
    }
    if (File.Exists( sLocalDirectory + sLine) == true)
        return sLine;
    else
        return "";
}

We also need to resolve the virtual directory to the actual physical directory like we do in IIS. We have already stored the mapping between the Actual and Virtual directory in Vdir.Dat. Remember in all the cases the file format is very important.


public string GetLocalPath(string sMyWebServerRoot, string sDirName)
{

    StreamReader sr;
    String sLine = "";
    String sVirtualDir = ""; 
    String sRealDir = "";
    int iStartPos = 0;


    //Remove extra spaces
    sDirName.Trim();



    // Convert to lowercase
    sMyWebServerRoot = sMyWebServerRoot.ToLower();

    // Convert to lowercase
    sDirName = sDirName.ToLower();

    
    try
    {
        //Open the Vdirs.dat to find out the list virtual directories
        sr = new StreamReader("data\\VDirs.Dat");

        while ((sLine = sr.ReadLine()) != null)
        {
            //Remove extra Spaces
            sLine.Trim();

            if (sLine.Length > 0)
            {
                //find the separator
                iStartPos = sLine.IndexOf(";");

                // Convert to lowercase
                sLine = sLine.ToLower();

                sVirtualDir = sLine.Substring(0,iStartPos);
                sRealDir = sLine.Substring(iStartPos + 1);

                if (sVirtualDir == sDirName)
                {
                    break;
                }
            }
        }
    }
    catch(Exception e)
    {
        Console.WriteLine("An Exception Occurred : " + e.ToString());
    }


    if (sVirtualDir == sDirName)
        return sRealDir;
    else
        return "";
}

Imtiaz Alam is a Senior Developer, currently residing in Phoenix, Arizona. He has more than five years of development experience in developing Mirosoft based Solution.

Imtiaz Alam is a Senior Developer, currently residing in Phoenix, Arizona. He has more than five years of development experience in developing Mirosoft based Solution. He can be reached at alamimtiaz@hotmail.com

Comments

  • Re: [1775] Create your own Web Server using C#

    Posted by michemal on 22 Jun 2007

    I was looking for a web server and came across a couple of other
    options, of course there is cassni / aka webdev but i tried this http://www.neokernel.com serv...

  • compression?

    Posted by rahulgarware on 01 Dec 2005

    How do you extend this to enable HTTP data compression?
    header:
    content-encoding=gzip

  • No Entry Point

    Posted by Aschehoug on 29 Jul 2005

    This code has no entry point. When compiling, I only get "error CS5001: Program 'c:\MyWebServer\MyWebServer.exe' does not have an entry point defined". I know that it is looking for a "Main()", but I ...

  • Posted by Michael H on 07 Sep 2004

    Hehe, I moved permanently to C# only a month or 2 after
    creating this thread :).

    I now have trouble reading VB code. Array access looks like
    function calls, etc... :cool:

  • Posted by SErhio on 07 Sep 2004

    i find c# more comprehensible then VB.
    for a C# programmer is more difficult for read VB code...