一个webseveice的例子

web

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
   {
    //Open the Vdirs.dat to find out the list virtual directories
    sr = new StreamReader("data\\Mime.Dat");
    while ((sLine = sr.ReadLine()) != null)
    {
     sLine.Trim();
     if (sLine.Length > 0)
     {
      //find the separator
      iStartPos = sLine.IndexOf(";");
      
      // Convert to lower case
      sLine = sLine.ToLower();
      
      sMimeExt = sLine.Substring(0,iStartPos);
      sMimeType = sLine.Substring(iStartPos + 1);
      
      if (sMimeExt == sFileExt)
       break;
     }
    }
   }
   catch (Exception e)
   {
    Console.WriteLine("An Exception Occurred : " + e.ToString());
   }
   if (sMimeExt == sFileExt)
    return sMimeType;
   else
    return "";
  }

  /// <summary>
  /// Returns the Physical Path
  /// </summary>
  /// <param name="sMyWebServerRoot">Web Server Root Directory</param>
  /// <param name="sDirName">Virtual Directory </param>
  /// <returns>Physical local Path</returns>
  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();
   //Remove the slash
   //sDirName = sDirName.Substring(1, sDirName.Length - 2);

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

   Console.WriteLine("Virtual Dir : " + sVirtualDir);
   Console.WriteLine("Directory   : " + sDirName);
   Console.WriteLine("Physical Dir: " + sRealDir);
   if (sVirtualDir == sDirName)
    return sRealDir;
   else
    return "";
  }
  

  /// <summary>
  /// This function send the Header Information to the client (Browser)
  /// </summary>
  /// <param name="sHttpVersion">HTTP Version</param>
  /// <param name="sMIMEHeader">Mime Type</param>
  /// <param name="iTotBytes">Total Bytes to be sent in the body</param>
  /// <param name="mySocket">Socket reference</param>
  /// <returns></returns>
  public void SendHeader(string sHttpVersion, string sMIMEHeader, int iTotBytes, string sStatusCode, ref Socket mySocket)
  {
   String sBuffer = "";
   
   // if Mime type is not provided set default to text/html
   if (sMIMEHeader.Length == 0 )
   {
    sMIMEHeader = "text/html";  // Default Mime Type is text/html
   }
   sBuffer = sBuffer + sHttpVersion + sStatusCode + "\r\n";
   sBuffer = sBuffer + "Server: cx1193719-b\r\n";
   sBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";
   sBuffer = sBuffer + "Accept-Ranges: bytes\r\n";
   sBuffer = sBuffer + "Content-Length: " + iTotBytes + "\r\n\r\n";
   
   Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);
   SendToBrowser( bSendData, ref mySocket);
   Console.WriteLine("Total Bytes : " + iTotBytes.ToString());
  }

  /// <summary>
  /// Overloaded Function, takes string, convert to bytes and calls
  /// overloaded sendToBrowserFunction.
  /// </summary>
  /// <param name="sData">The data to be sent to the browser(client)</param>
  /// <param name="mySocket">Socket reference</param>
  public void SendToBrowser(String sData, ref Socket mySocket)
  {
   SendToBrowser (Encoding.ASCII.GetBytes(sData), ref mySocket);
  }

  /// <summary>
  /// Sends data to the browser (client)
  /// </summary>
  /// <param name="bSendData">Byte Array</param>
  /// <param name="mySocket">Socket reference</param>
  public void SendToBrowser(Byte[] bSendData, ref Socket mySocket)
  {
   int numBytes = 0;
   
   try
   {
    if (mySocket.Connected)
    {
     if (( numBytes = mySocket.Send(bSendData, bSendData.Length,0)) == -1)
      Console.WriteLine("Socket Error cannot Send Packet");
     else
     {
      Console.WriteLine("No. of bytes send {0}" , numBytes);
     }
    }
    else
     Console.WriteLine("Connection Dropped....");
   }
   catch (Exception  e)
   {
    Console.WriteLine("Error Occurred : {0} ", e );
       
   }
  }

  // Application Starts Here..
  public static void Main()
  {
   MyWebServer MWS = new MyWebServer();
  }

  //This method Accepts new connection and
  //First it receives the welcome massage from the client,
  //Then it sends the Current date time to the Client.
  public void StartListen()
  {
   int iStartPos = 0;
   String sRequest;
   String sDirName;
   String sRequestedFile;
   String sErrorMessage;
   String sLocalDir;
   String sMyWebServerRoot = "C:\\MyWebServerRoot\\";
   String sPhysicalFilePath = "";
   String sFormattedMessage = "";
   String sResponse = "";
   
   
   
   while(true)
   {
    //Accept a new connection
    Socket mySocket = myListener.AcceptSocket() ;
    Console.WriteLine ("Socket Type " +  mySocket.SocketType );
    if(mySocket.Connected)
    {
     Console.WriteLine("\nClient Connected!!\n==================\nCLient IP {0}\n",
      mySocket.RemoteEndPoint) ;
    
     //make a byte array and receive data from the client
     Byte[] bReceive = new Byte[1024] ;
     int i = mySocket.Receive(bReceive,bReceive.Length,0) ;

     
     //Convert Byte to String
     string sBuffer = Encoding.ASCII.GetString(bReceive);
  
     
     //At present we will only deal with GET type
     if (sBuffer.Substring(0,3) != "GET" )
     {
      Console.WriteLine("Only Get Method is supported..");
      mySocket.Close();
      return;
     }
     
     // Look for HTTP request
     iStartPos = sBuffer.IndexOf("HTTP",1);

     // Get the HTTP text and version e.g. it will return "HTTP/1.1"
     string sHttpVersion = sBuffer.Substring(iStartPos,8);
        
                  
     // Extract the Requested Type and Requested file/directory
     sRequest = sBuffer.Substring(0,iStartPos - 1);
        
          
     //Replace backslash with Forward Slash, if Any
     sRequest.Replace("file://\\","/");

     //If file name is not supplied add forward slash to indicate
     //that it is a directory and then we will look for the
     //default file name..
     if ((sRequest.IndexOf(".") <1) && (!sRequest.EndsWith("/")))
     {
      sRequest = sRequest + "/";
     }

     //Extract the requested file name
     iStartPos = sRequest.LastIndexOf("/") + 1;
     sRequestedFile = sRequest.Substring(iStartPos);
     
     //Extract The directory Name
     sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/")-3);
     
      
     
     /////////////////////////////////////////////////////////////////////
     // Identify the Physical Directory
     /////////////////////////////////////////////////////////////////////
     if ( sDirName == "/")
      sLocalDir = sMyWebServerRoot;
     else
     {
      //Get the Virtual Directory
      sLocalDir = GetLocalPath(sMyWebServerRoot, sDirName);
     }

     Console.WriteLine("Directory Requested : " +  sLocalDir);
     //If the physical directory does not exists then
     // dispaly the error message
     if (sLocalDir.Length == 0 )
     {
      sErrorMessage = "<H2>Error!! Requested Directory does not exists</H2><Br>";
      //sErrorMessage = sErrorMessage + "Please check data\\Vdirs.Dat";
      //Format The Message
      SendHeader(sHttpVersion,  "", sErrorMessage.Length, " 404 Not Found", ref mySocket);
      //Send to the browser
      SendToBrowser(sErrorMessage, ref mySocket);
      mySocket.Close();
      continue;
     }
     
     /////////////////////////////////////////////////////////////////////
     // Identify the File Name
     /////////////////////////////////////////////////////////////////////
     //If The file name is not supplied then look in the default file list
     if (sRequestedFile.Length == 0 )
     {
      // Get the default filename
      sRequestedFile = GetTheDefaultFileName(sLocalDir);
      if (sRequestedFile == "")
      {
       sErrorMessage = "<H2>Error!! No Default File Name Specified</H2>";
       SendHeader(sHttpVersion,  "", sErrorMessage.Length, " 404 Not Found", ref mySocket);
       SendToBrowser ( sErrorMessage, ref mySocket);
       mySocket.Close();
       return;
      }
     }
     

     /////////////////////////////////////////////////////////////////////
     // Get TheMime Type
     /////////////////////////////////////////////////////////////////////
     
     String sMimeType = GetMimeType(sRequestedFile);

     //Build the physical path
     sPhysicalFilePath = sLocalDir + sRequestedFile;
     Console.WriteLine("File Requested : " +  sPhysicalFilePath);
     
     
     if (File.Exists(sPhysicalFilePath) == false)
     {
     
      sErrorMessage = "<H2>404 Error! File Does Not Exists...</H2>";
      SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found", ref mySocket);
      SendToBrowser( sErrorMessage, ref mySocket);
      Console.WriteLine(sFormattedMessage);
     }
    
     else
     {
      int iTotBytes=0;
      sResponse ="";

      FileStream fs = new FileStream(sPhysicalFilePath, FileMode.Open,  FileAccess.Read, FileShare.Read);
      // Create a reader that can read bytes from the FileStream.
      
      BinaryReader reader = new BinaryReader(fs);
      byte[] bytes = new byte[fs.Length];
      int read;
      while((read = reader.Read(bytes, 0, bytes.Length)) != 0)
      {
       // Read from the file and write the data to the network
       sResponse = sResponse + Encoding.ASCII.GetString(bytes,0,read);
       iTotBytes = iTotBytes + read;
      }
      reader.Close();
      fs.Close();
      SendHeader(sHttpVersion,  sMimeType, iTotBytes, " 200 OK", ref mySocket);
      SendToBrowser(bytes, ref mySocket);
      
      //mySocket.Send(bytes, bytes.Length,0);
     }
     mySocket.Close();      
    }
   }
  }
}
}
  

时间: 2025-01-02 14:44:35

一个webseveice的例子的相关文章

一断冒泡排序和一个闭包的例子。

写一断冒泡排序和一个闭包的例子,提供新手学习使用. 冒泡排序 var bubbleSort = function(array){       var i = 0, len = array.length, j, d;               for(; i<len; i++){           for(j=0; j<len; j++){               if(array[i] < array[j]){                   d = array[j];  

从一个MysqL的例子来学习查询语句

mysql|语句 自上学这么多年以来,得出了从一个例子入手来学习是最快最有效,并能培养出很强的实践能力,这是一种很 好的学习方法.不访试试.比如看一本书的时候从各章节的例子入手,找出不了解的以及不懂的还是新知识, 进而有针对性的学习.看看下面的例子: <?php $ip = getenv("REMOTE_ADDR"); //echo "$ip"; $conn=mysql_connect('ip','root','****');   mysql_select_d

calcite-求一个linQ4j的例子。

问题描述 求一个linQ4j的例子. 与数据库连接的 简单例子即好 .与数据库连接的 简单例子即好 .与数据库连接的 简单例子即好 .30字... 解决方案 一个DOM4J的例子

对象-请问各位,我这样理解访问者模式正确吗,一个简单的例子

问题描述 请问各位,我这样理解访问者模式正确吗,一个简单的例子 package test; public class Client{ //数据对象二 顾客 public static void main(String[] args) { //当顾客进饭店吃饭,他不会直接跟厨师打交道, //1.饭店主要是炒菜,这时,厨师会炒很多菜 但是不知道炒哪个菜, 厨房与顾客 不具备炒菜的功能, //所以炒菜可以是厨师的功能,但是需要一个中间人来告诉厨师炒什么菜,那么我们就定义一个菜单,相当于访问者,访问厨师

c++问题-关于c++ primer中一个友元的例子

问题描述 关于c++ primer中一个友元的例子 C++primer中的一个例子,关于友元,在VS2015报错,定义了两个类Screen和window-mgr,window-mgr作为Screen的友元,但是提示Screen没有构造函数 解决方案 贴出你的代码,你如果有拷贝之类的操作但是没有定义拷贝构造函数,或者初始化对象,但是没有提供无参数公共构造函数等,都会报错. 解决方案二: C++Primer之友元<C++ Primer>中的TextQuery例子 解决方案三: 这个其实跟友元没关系

求一个简单多线程例子

问题描述 求一个简单多线程例子 解决方案 解决方案二:http://blog.csdn.net/jinjazz/archive/2008/05/06/2397136.aspx

《Python数据科学实践指南》——0.4 一个简单的例子

0.4 一个简单的例子 下面是一段用Python编写的有趣的代码,这里所用的模块并不会在本书中进行讲解,仅仅是向购买本书的你表示我的感激. 代码清单如下: # ! /usr/bin/python # -- coding: utf-8 -- import sys from colorama import init init(strip=not sys.stdout.isatty()) from termcolor import cprint from pyfiglet import figlet_

《Python数据科学实践指南》一0.4 一个简单的例子

0.4 一个简单的例子 下面是一段用Python编写的有趣的代码,这里所用的模块并不会在本书中进行讲解,仅仅是向购买本书的你表示我的感激. 代码清单如下: # ! /usr/bin/python # -- coding: utf-8 -- import sys from colorama import init init(strip=not sys.stdout.isatty()) from termcolor import cprint from pyfiglet import figlet_

从一个MySQL的例子来学习查询语句_Mysql

自上学这么多年以来,得出了从一个例子入手来学习是最快最有效,并能培养出很强的实践能力,这是一种很好的学习方法.不访试试.比如看一本书的时候从各章节的例子入手,找出不了解的以及不懂的还是新知识,  进而有针对性的学习.看看下面的例子:  <?php  $ip = getenv("REMOTE_ADDR");  //echo "$ip";  $conn=mysql_connect('ip','root','****');    mysql_select_db('d