Creating your own Web Server using C#

Environment: C#, .Net

SUMMARY: This article explains how to write a simple web server application using C#. Though it can be developed in any .net supported language, I chose C# for this example. The code is compiled using beta2. Microsoft (R) Visual C# Compiler Version 7.00.9254 [CLR version v1.0.2914]. It can be used with Beta1 with some minor modification. This application can co-exists with IIS or any web server, the key is to choose any free port. I assume that the user has some basic understanding of .net and C# or VB.Net. This Web server just returns html formatted files and also supports images. It does not loads the embedded image or supports any kind of scripting. I have developed a console-based application for simplicity.

First we will define the root folder for our web server. Eg: C:\MyPersonalwebServer, and will create a Data directory underneath, our root directory Eg: C:\MyPersonalwebServer\Data. We will Create three files under data directory i.e.

  • Mimes.Dat
  • Vdirs.Dat
  • Default.Dat

Mime.Dat will have the mime type supported by our web server. The format will be ; e.g.

.html; text/html
.htm; text/html
.bmp; image/bmp

VDirs.Dat will have the virtual directory Information. The format will be ; e.g.

/; C:\myWebServerRoot/
test/; C:\myWebServerRoot\Imtiaz\

Default.Dat will have the virtual directory Information; e.g.

default.html
default.htm
Index.html
Index.htm;

We will store all the information in plain text file for simplicity, we can use XML, registry or even hard code it. Before proceeding to our code let us first look the header information which browser will pass while requesting for our web site

Let say we request for test.html we type http://localhost:5050/test.html
(Remember to include port in the url), here what the web server gets..

GET /test.html HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
Accept-Language: en-usAccept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0; .NET CLR 1.0.2914)
Host: localhost:5050Connection: Keep-Alive

Let us dive into the code..

  1. // MyWebServer Written by Imtiaz Alam  
  2. namespace Imtiaz  
  3. {  
  4.     using System;  
  5.     using System.IO;  
  6.     using System.Net;  
  7.     using System.Net.Sockets;  
  8.     using System.Text;  
  9.     using System.Threading;  
  10.     class MyWebServer  
  11.     {  
  12.         private TcpListener myListener;  
  13.         private int port = 5050; // Select any free port you wish   
  14.                                  //The constructor which make the TcpListener start listening on th  
  15.                                  //given port. It also calls a Thread on the method StartListen().   
  16.         public MyWebServer()  
  17.         {  
  18.             try  
  19.             {  
  20.                 //start listing on the given port  
  21.                 myListener = new TcpListener(port);  
  22.                 myListener.Start();  
  23.                 Console.WriteLine("Web Server Running... Press ^C to Stop...");  
  24.                 //start the thread which calls the method 'StartListen'  
  25.                 Thread th = new Thread(new ThreadStart(StartListen));  
  26.                 th.Start();  
  27.             }  
  28.             catch (Exception e)  
  29.             {  
  30.                 Console.WriteLine("An Exception Occurred while Listening :" + e.ToString());  
  31.             }  
  32.         }  
  33.     }  
  34. }  
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.

  1. public string GetTheDefaultFileName(string sLocalDirectory)  
  2. {  
  3.     StreamReader sr;  
  4.     String sLine = "";  
  5.     try  
  6.     {  
  7.         //Open the default.dat to find out the list  
  8.         // of default file  
  9.         sr = new StreamReader("data\\Default.Dat");  
  10.         while ((sLine = sr.ReadLine()) != null)  
  11.         {  
  12.             //Look for the default file in the web server root folder  
  13.             if (File.Exists(sLocalDirectory + sLine) == true)  
  14.                 break;  
  15.         }  
  16.     }  
  17.     catch (Exception e)  
  18.     {  
  19.         Console.WriteLine("An Exception Occurred : " + e.ToString());  
  20.     }  
  21.     if (File.Exists(sLocalDirectory + sLine) == true)  
  22.         return sLine;  
  23.     else  
  24.         return "";  
  25. }  
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.
  1. public string GetLocalPath(string sMyWebServerRoot, string sDirName)  
  2. {  
  3.     StreamReader sr;  
  4.     String sLine = "";  
  5.     String sVirtualDir = "";  
  6.     String sRealDir = "";  
  7.     int iStartPos = 0;  
  8.     //Remove extra spaces  
  9.     sDirName.Trim();  
  10.     // Convert to lowercase  
  11.     sMyWebServerRoot = sMyWebServerRoot.ToLower();  
  12.     // Convert to lowercase  
  13.     sDirName = sDirName.ToLower();  
  14.     try  
  15.     {  
  16.         //Open the Vdirs.dat to find out the list virtual directories  
  17.         sr = new StreamReader("data\\VDirs.Dat");  
  18.         while ((sLine = sr.ReadLine()) != null)  
  19.         {  
  20.             //Remove extra Spaces  
  21.             sLine.Trim();  
  22.             if (sLine.Length > 0)  
  23.             {  
  24.                 //find the separator  
  25.                 iStartPos = sLine.IndexOf(";");  
  26.                 // Convert to lowercase  
  27.                 sLine = sLine.ToLower();  
  28.                 sVirtualDir = sLine.Substring(0, iStartPos);  
  29.                 sRealDir = sLine.Substring(iStartPos + 1);  
  30.                 if (sVirtualDir == sDirName)  
  31.                 {  
  32.                     break;  
  33.                 }  
  34.             }  
  35.         }  
  36.     }  
  37.     catch (Exception e)  
  38.     {  
  39.         Console.WriteLine("An Exception Occurred : " + e.ToString());  
  40.     }  
  41.     if (sVirtualDir == sDirName)  
  42.         return sRealDir;  
  43.     else  
  44.         return "";  
  45. }  
We also need to identify the Mime type, using the file extension supplied by the user
  1. public string GetMimeType(string sRequestedFile)  
  2. {  
  3.     StreamReader sr;  
  4.     String sLine = "";  
  5.     String sMimeType = "";  
  6.     String sFileExt = "";  
  7.     String sMimeExt = "";  
  8.     // Convert to lowercase  
  9.     sRequestedFile = sRequestedFile.ToLower();  
  10.     int iStartPos = sRequestedFile.IndexOf(".");  
  11.     sFileExt = sRequestedFile.Substring(iStartPos);  
  12.     try  
  13.     {  
  14.         //Open the Vdirs.dat to find out the list virtual directories  
  15.         sr = new StreamReader("data\\Mime.Dat");  
  16.         while ((sLine = sr.ReadLine()) != null)  
  17.         {  
  18.             sLine.Trim();  
  19.             if (sLine.Length > 0)  
  20.             {  
  21.                 //find the separator  
  22.                 iStartPos = sLine.IndexOf(";");  
  23.                 // Convert to lower case  
  24.                 sLine = sLine.ToLower();  
  25.                 sMimeExt = sLine.Substring(0, iStartPos);  
  26.                 sMimeType = sLine.Substring(iStartPos + 1);  
  27.                 if (sMimeExt == sFileExt)  
  28.                     break;  
  29.             }  
  30.         }  
  31.     }  
  32.     catch (Exception e)  
  33.     {  
  34.         Console.WriteLine("An Exception Occurred : " + e.ToString());  
  35.     }  
  36.     if (sMimeExt == sFileExt)  
  37.         return sMimeType;  
  38.     else  
  39.         return "";  
  40. }  

Now we will write the function, to build and sends header information to the browser (client)

  1. public void SendHeader(string sHttpVersion, string sMIMEHeader, int iTotBytes, string sStatusCode, ref Socket mySocket)  
  2. {  
  3.     String sBuffer = "";  
  4.     // if Mime type is not provided set default to text/html  
  5.     if (sMIMEHeader.Length == 0)  
  6.     {  
  7.         sMIMEHeader = "text/html";// Default Mime Type is text/html  
  8.     }  
  9.     sBuffer = sBuffer + sHttpVersion + sStatusCode + "\r\n";  
  10.     sBuffer = sBuffer + "Server: cx1193719-b\r\n";  
  11.     sBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";  
  12.     sBuffer = sBuffer + "Accept-Ranges: bytes\r\n";  
  13.     sBuffer = sBuffer + "Content-Length: " + iTotBytes + "\r\n\r\n";  
  14.     Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);  
  15.     SendToBrowser(bSendData, ref mySocket);  
  16.     Console.WriteLine("Total Bytes : " + iTotBytes.ToString());  
  17. }  
The SendToBrowser function sends information to the browser. This is an overloaded function.
  1. public void SendToBrowser(String sData, ref Socket mySocket)  
  2. {  
  3.     SendToBrowser(Encoding.ASCII.GetBytes(sData), ref mySocket);  
  4. }  
  5. public void SendToBrowser(Byte[] bSendData, ref Socket mySocket)  
  6. {  
  7.     int numBytes = 0;  
  8.     try  
  9.     {  
  10.         if (mySocket.Connected)  
  11.         {  
  12.             if ((numBytes = mySocket.Send(bSendData, bSendData.Length, 0)) == -1)  
  13.                 Console.WriteLine("Socket Error cannot Send Packet");  
  14.             else  
  15.             {  
  16.                 Console.WriteLine("No. of bytes send {0}", numBytes);  
  17.             }  
  18.         }  
  19.         else Console.WriteLine("Connection Dropped....");  
  20.     }  
  21.     catch (Exception e)  
  22.     {  
  23.         Console.WriteLine("Error Occurred : {0} ", e);  
  24.     }  
  25. }  
We now have all the building blocks ready, now we will delve into the key function of our application.  
  1. public void StartListen()  
  2. {  
  3.     int iStartPos = 0;  
  4.     String sRequest;  
  5.     String sDirName;  
  6.     String sRequestedFile;  
  7.     String sErrorMessage;  
  8.     String sLocalDir;  
  9.     String sMyWebServerRoot = "C:\\MyWebServerRoot\\";  
  10.     String sPhysicalFilePath = "";  
  11.     String sFormattedMessage = "";  
  12.     String sResponse = "";  
  13.     while (true)  
  14.     {  
  15.         //Accept a new connection  
  16.         Socket mySocket = myListener.AcceptSocket();  
  17.         Console.WriteLine("Socket Type " + mySocket.SocketType);  
  18.         if (mySocket.Connected)  
  19.         {  
  20.             Console.WriteLine("\nClient Connected!!\n==================\n  
  21.             CLient IP { 0}\n", mySocket.RemoteEndPoint) ;  
  22.         //make a byte array and receive data from the client   
  23. Byte[] bReceive = new Byte[1024];  
  24.             int i = mySocket.Receive(bReceive, bReceive.Length, 0);  
  25.             //Convert Byte to String  
  26.             string sBuffer = Encoding.ASCII.GetString(bReceive);  
  27.             //At present we will only deal with GET type  
  28.             if (sBuffer.Substring(0, 3) != "GET")  
  29.             {  
  30.                 Console.WriteLine("Only Get Method is supported..");  
  31.                 mySocket.Close();  
  32.                 return;  
  33.             }  
  34.             // Look for HTTP request  
  35.             iStartPos = sBuffer.IndexOf("HTTP", 1);  
  36.             // Get the HTTP text and version e.g. it will return "HTTP/1.1"  
  37.             string sHttpVersion = sBuffer.Substring(iStartPos, 8);  
  38.             // Extract the Requested Type and Requested file/directory  
  39.             sRequest = sBuffer.Substring(0, iStartPos - 1);  
  40.             //Replace backslash with Forward Slash, if Any  
  41.             sRequest.Replace("\\", "/");  
  42.             //If file name is not supplied add forward slash to indicate   
  43.             //that it is a directory and then we will look for the   
  44.             //default file name..  
  45.             if ((sRequest.IndexOf(".") < 1) && (!sRequest.EndsWith("/")))  
  46.             {  
  47.                 sRequest = sRequest + "/";  
  48.             }  
  49.             //Extract the requested file name  
  50.             iStartPos = sRequest.LastIndexOf("/") + 1;  
  51.             sRequestedFile = sRequest.Substring(iStartPos);  
  52.             //Extract The directory Name  
  53.             sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/") - 3);  
  54.         }  
  55.     }  
  56. }  
The code is self-explanatory. It receives the request, converts it into string from bytes then look for the request type, extracts the HTTP Version, file and directory information.
  1. /////////////////////////////////////////////////////////////////////  
  2. // Identify the Physical Directory  
  3. /////////////////////////////////////////////////////////////////////  
  4. if (sDirName == "/")  
  5.     sLocalDir = sMyWebServerRoot;  
  6. else  
  7. {  
  8.     //Get the Virtual Directory  
  9.     sLocalDir = GetLocalPath(sMyWebServerRoot, sDirName);  
  10. }  
  11. Console.WriteLine("Directory Requested : " + sLocalDir);  
  12. //If the physical directory does not exists then  
  13. // dispaly the error message  
  14. if (sLocalDir.Length == 0)  
  15. {  
  16.     sErrorMessage = "<H2>Error!! Requested Directory does not exists</H2><Br>";  
  17.     //sErrorMessage = sErrorMessage + "Please check data\\Vdirs.Dat";  
  18.     //Format The Message  
  19.     SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found"ref mySocket);  
  20.     //Send to the browser  
  21.     SendToBrowser(sErrorMessage, ref mySocket);  
  22.     mySocket.Close();  
  23.     continue;  
  24. }  
Note: Microsoft Internet Explorer usually displays a 'friendy' HTTP Error Page if you want to display our error message then you need to disable the 'Show friendly HTTP error messages' option under the 'Advanced' tab in Tools->Internet Options. Next we look if the directory name is supplied, we call GetLocalPath function to get the physical directory information, if the directory not found (or does not mapped with entry in Vdir.Dat) error message is sent to the browser.. Next we will identify the file name, if the filename is not supplied by the user we will call the GetTheDefaultFileName function to retrieve the filename, if error occurred it is thrown to browser.
  1. /////////////////////////////////////////////////////////////////////  
  2. // Identify the File Name  
  3. /////////////////////////////////////////////////////////////////////  
  4. //If The file name is not supplied then look in the default file list  
  5. if (sRequestedFile.Length == 0)  
  6. {  
  7.     // Get the default filename  
  8.     sRequestedFile = GetTheDefaultFileName(sLocalDir);  
  9.     if (sRequestedFile == "")  
  10.     {  
  11.         sErrorMessage = "<H2>Error!! No Default File Name Specified</H2>";  
  12.         SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found",  
  13.         ref mySocket);  
  14.         SendToBrowser(sErrorMessage, ref mySocket);  
  15.         mySocket.Close();  
  16.         return;  
  17.     }  
  18. }  
Then we need to indentify the Mime type
  1. /////////////////////////////////////////////////////////////////////  
  2. // Get TheMime Type  
  3. /////////////////////////////////////////////////////////////////////  
  4. String sMimeType = GetMimeType(sRequestedFile);  
  5. //Build the physical path  
  6. sPhysicalFilePath = sLocalDir + sRequestedFile;  
  7. Console.WriteLine("File Requested : " + sPhysicalFilePath);  
Now the final steps of opening the requested file and sending it to the browser..
  1. if (File.Exists(sPhysicalFilePath) == false)  
  2. {  
  3.     sErrorMessage = "<H2>404 Error! File Does Not Exists...</H2>";  
  4.     SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found"ref mySocket);  
  5.     SendToBrowser(sErrorMessage, ref mySocket);  
  6.     Console.WriteLine(sFormattedMessage);  
  7. }  
  8. else  
  9. {  
  10.     int iTotBytes = 0;  
  11.     sResponse = "";  
  12.     FileStream fs = new FileStream(sPhysicalFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);  
  13.     // Create a reader that can read bytes from the FileStream.  
  14.     BinaryReader reader = new BinaryReader(fs);  
  15.     byte[] bytes = new byte[fs.Length];  
  16.     int read;  
  17.     while ((read = reader.Read(bytes, 0, bytes.Length)) != 0)  
  18.     {  
  19.         // Read from the file and write the data to the network  
  20.         sResponse = sResponse + Encoding.ASCII.GetString(bytes, 0, read);  
  21.         TotBytes = iTotBytes + read;  
  22.     }  
  23.     reader.Close();  
  24.     fs.Close();  
  25.     SendHeader(sHttpVersion, sMimeType, iTotBytes, " 200 OK"ref mySocket);  
  26.     SendToBrowser(bytes, ref mySocket);  
  27.     //mySocket.Send(bytes, bytes.Length,0);  
  28. }  
  29. mySocket.Close();  
Compilation and Execution

To compile the program from the command line:

WebSerImgIMA1.gif

In my version of .net I dont need to specify any library name, may be for old version we require to add the reference to dll, using /r parameter.

To run the application simply type the application name and press Enter..

WebSerImgIMA2.gif

Now, let say user send the request, our web server will identify the default file name and sends to the browser.

WebSerImgIMA3.gif

User can also request the Image file..

WebSerImgIMA4.gif


Possible Improvements

There are many improvements can be made to the WebServer application. Currently it does not supports embedded images and no supports for scripting. We can write our own Isapi filter for the same or we can also use the IIS isapi filter for our learning purpose.

Conclusion

This article gives very basic idea of writing Web server application, lots of improvement can be done. Ill appreciate if I can get any comments on improving the same. I am also looking forward for adding the capabilities of calling Microsoft Isapi Filter from this application.


Similar Articles