日期:2012-09-24  浏览次数:20454 次

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());
   }
  }

  /// <summary>
  /// Returns The Default File Name
  /// Input : WebServerRoot Folder
  /// Output: Default File Name
  /// </summary>
  /// <param name="sMyWebServerRoot"></param>
  /// <returns></returns>
  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 "";
  }

  /// <summary>
  /// This function takes FileName as Input and returns the mime type..
  /// </summary>
  /// <param name="sRequestedFile">To indentify the Mime Type</param>
  /// <returns>Mime Type</returns>
  public string GetMimeType(string sRequestedFile)
  {
   
   StreamReader sr;
   String sLine = "";
   String sMimeType = "";
   String sFileExt = "";
   String sMimeExt = "";
   
   // Convert to lowercase
   sRequestedFile = sRequestedFile.ToLower();
   
   int iStartPos = sRequestedFile.IndexOf(".");
   sFileExt = sRequestedFile.Substring(iStartPos);
   
   try
   {