modernsky2003

备份与恢复数据库 C#实现WEB服务器

事务处理:
private void Button2_Click(object sender, System.EventArgs e)
  {
   SqlConnection cn=new SqlConnection("server=.;database=pubs;uid=sa;pwd=");
   cn.Open();
   SqlCommand cmd=cn.CreateCommand();
   SqlTransaction ta=cn.BeginTransaction();
   cmd.Connection=cn;
   cmd.Transaction=ta;
   try
   {
    cmd.CommandText="update account set usermoney=3.22 where userid='jack'";
    cmd.ExecuteNonQuery(); 
    cmd.CommandText="update account set usermoney='3.22' where userid='rose'";
    cmd.ExecuteNonQuery();
    ta.Commit();
    //Label1.Text="succeed!";
   }
   catch
   {
    ta.Rollback();
    //Label1.Text=ex.Message.ToString();
   }
   finally
   {
    cn.Close();
   }
  }
 

private void Page_Load(object sender, System.EventArgs e)
  {
   if(!IsPostBack)
   {
    SqlConnection cn=new SqlConnection("server=.;uid=sa;pwd=");
    SqlDataAdapter da=new SqlDataAdapter("sp_helpdb",cn);
    DataTable dt=new DataTable();
    da.Fill(dt);

    DataGrid1.DataSource=dt;
    DataGrid1.DataBind();

    ListBox1.DataSource=dt;
    ListBox1.DataTextField="name";
    ListBox1.DataValueField="name";
    ListBox1.DataBind();
    
   }
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Button2.Click += new System.EventHandler(this.Button2_Click);
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Button1_Click(object sender, System.EventArgs e)
  {
   if(ListBox1.SelectedIndex>-1)
   {
    SqlConnection cn=new SqlConnection("server=.;uid=sa;pwd=");
    string str=@"backup database @database to disk=@path with password=@password";
    SqlCommand cmd=new SqlCommand(str,cn);
    cmd.Parameters.Add("@database",ListBox1.SelectedItem.Text);
    cmd.Parameters.Add("@path",@"f:\"+ListBox1.SelectedItem.Text+".bak");
    cmd.Parameters.Add("@password",TextBox1.Text);   
    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();
   }
  }

  private void Button2_Click(object sender, System.EventArgs e)
  {
   if(ListBox1.SelectedIndex!=-1)
   {
    SqlConnection cn=new SqlConnection("server=.;uid=sa;pwd=");
    string str=@"restore database @database from disk=@path with password=@password";
    SqlCommand cmd=new SqlCommand(str,cn);
    cmd.Parameters.Add("@database",ListBox1.SelectedItem.Text);
    cmd.Parameters.Add("@path",File1.PostedFile.FileName);
    cmd.Parameters.Add("@password",TextBox1.Text);   
    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();
   }
  }
 }



private void Button1_Click(object sender, System.EventArgs e)
  {
   DataSet ds=new DataSet();
   ds=(DataSet)this.ViewState["ds"];
   DataRow dr=ds.Tables["categories"].NewRow();
   dr[0]=TextBox1.Text;
   dr[1]=TextBox2.Text;
   dr[2]=TextBox3.Text;
   ds.Tables["categories"].Rows.Add(dr);
   this.ViewState["ds"]=ds;
   DataGrid2.DataSource = ds.Tables["categories"].DefaultView;
   DataGrid2.DataBind();
  }

  private void Button5_Click(object sender, System.EventArgs e)
  {
   DataSet ds=new DataSet();
   ds=(DataSet)this.ViewState["ds"];
   DataRow[] dr=ds.Tables["categories"].Select("CategoryID='" + TextBox7.Text+"'");
   dr[0][1]=TextBox6.Text;
   dr[0][2]=TextBox5.Text;
   this.ViewState["ds"]=ds;
   DataGrid2.DataSource = ds.Tables["categories"].DefaultView;
   DataGrid2.DataBind();
  }

  private void Button3_Click(object sender, System.EventArgs e)
  {
   DataSet ds=new DataSet();
   ds=(DataSet)this.ViewState["ds"];
   DataRow[] dr=ds.Tables["categories"].Select("CategoryID='" + TextBox4.Text+"'");
   dr[0].Delete();
   this.ViewState["ds"]=ds;
   DataGrid2.DataSource = ds.Tables["categories"].DefaultView;
   DataGrid2.DataBind();
  }

  private void Button2_Click(object sender, System.EventArgs e)
  {
   DataSet ds=new DataSet();
   ds=(DataSet)this.ViewState["ds"];
   SqlDataAdapter da=new SqlDataAdapter();
   da=(SqlDataAdapter)this.Session["da"];
   SqlCommandBuilder sqlCmdBuilder=new SqlCommandBuilder(da);
   if(ds.HasChanges())
   {
    da.Update(ds.Tables["categories"].GetChanges());
    ds.Tables["categories"].AcceptChanges();
   }
   DataGrid3.DataSource = ds.Tables["categories"].DefaultView;
   DataGrid3.DataBind();
  }


void ShowData()
  {
   SqlConnection cn=new  SqlConnection();
   cn.ConnectionString="server=.;database=pubs;uid=sa;pwd=;";
   String sql;
   sql="select emp_id,fname,lname,job_id,pub_id,hire_date from employee_new where emp_id='" + DropDownList1.SelectedItem.Value + "'";
   
   SqlCommand cmd;  
   cmd=new SqlCommand(sql,cn);
   cn.Open();
   SqlDataReader dr;
   dr=cmd.ExecuteReader();//将CommandText发送到Connection并生成一个SqlDataReader。
   dr.Read();
   TextBox1.Text=dr["emp_id"].ToString();
   TextBox2.Text=dr["fname"].ToString();
   TextBox3.Text=dr["lname"].ToString();
   TextBox4.Text=dr["job_id"].ToString();
   TextBox5.Text=dr["pub_id"].ToString();
   TextBox6.Text=dr["hire_date"].ToString();
   dr.Close();//当正在使用 SqlDataReader 时,关联的 SqlConnection 在忙于服务 SqlDataReader,而且除了关闭以外不能对 SqlConnection 执行其他任何操作。除非调用 SqlDataReader 的 Close 方法,否则会一直处于此状态。
   cn.Close();

   sql="select emp_id,fname,lname,job_id,pub_id,hire_date from employee_new";
   cmd=new SqlCommand(sql,cn);
   cn.Open();
   DataGrid1.DataSource=cmd.ExecuteReader();
   DataGrid1.DataBind();
  }

  private void Button2_Click(object sender, System.EventArgs e)
  {
   ClearData();
  }

  void ClearData()
  {
   TextBox1.Text="";
   TextBox2.Text="";
   TextBox3.Text="";
   TextBox4.Text="";
   TextBox5.Text="";
   TextBox6.Text="";
  }

  private void Button3_Click(object sender, System.EventArgs e)
  {
   InsertData();
  }

  void InsertData()
  {
   String sql;
   sql="insert into employee_new(emp_id,fname,lname,job_id,pub_id,hire_date) values(";
   sql+="'" + TextBox1.Text + "',";
   sql+="'" + TextBox2.Text + "',";
   sql+="'" + TextBox3.Text + "',";
   sql+="'" + TextBox4.Text + "',";
   sql+="'" + TextBox5.Text + "',";
   sql+="'" + TextBox6.Text + "')";
   
   SqlConnection cn=new  SqlConnection();
   cn.ConnectionString="server=.;database=pubs;uid=sa;pwd=;";
   
   SqlCommand cmd;   
   cmd=new SqlCommand(sql,cn);
   cn.Open();
   int Added;
   Added=cmd.ExecuteNonQuery();
   cn.Close();
   Label6.Text=Added.ToString();
   if (Added>0)
   {
    InitID();
    ShowData();
   }
  }

  private void Button4_Click(object sender, System.EventArgs e)
  {
   UpdateData();
  }

  void UpdateData()
  {
   String sql;
   sql="update employee_new set ";//注意set后面要留空格
   sql+="fname='" + TextBox2.Text + "',";
   sql+="lname='" + TextBox3.Text + "',";
   sql+="job_id='" + TextBox4.Text + "',";
   sql+="pub_id='" + TextBox5.Text + "',";
   sql+="hire_date='" + TextBox6.Text + "'";
   //sql+=" where emp_id='" + DropDownList1.SelectedItem.Value + "'";//注意where前面要留空格
   sql+=" where emp_id='" + TextBox1.Text + "'";//注意where前面要留空格
   
   SqlConnection cn=new  SqlConnection();
   cn.ConnectionString="server=.;database=pubs;uid=sa;pwd=;";
   
   SqlCommand cmd;   
   cmd=new SqlCommand(sql,cn);
   cn.Open();
   int Updated;
   Updated=cmd.ExecuteNonQuery();
   cn.Close();
   Label6.Text=Updated.ToString();
  }

  private void Button5_Click(object sender, System.EventArgs e)
  {
   DeleteData();
  }

  void DeleteData()
  {
   String sql;
   sql="delete employee_new where emp_id='" + TextBox1.Text + "'";
   
   SqlConnection cn=new  SqlConnection();
   cn.ConnectionString="server=.;database=pubs;uid=sa;pwd=;";
   
   SqlCommand cmd; 
   cmd=new SqlCommand(sql,cn);
   cn.Open();
   int Deleted;
   Deleted=cmd.ExecuteNonQuery();
   cn.Close();
   Label6.Text=Deleted.ToString();
   if (Deleted>0)
   {
    InitID();
    ShowData();
   }
  }

  private void Button6_Click(object sender, System.EventArgs e)
  {
   InsertDataOK();
  }

  void InsertDataOK()
  {
   //1、使用带参数的sql语句,可以确保从外部源接收到的值仅作为值传递,而不作为sql语句的一部分来传递,可以防止参数受到SQL注入式攻击。
   //update employee_new set fname='panda' Where emp_id = 'A-C71970F delete employee_new'
   //select * from userinfo where userid='panda' or '1'='1'
   //2、可以在sql语句中包含引号
   //update employee_new set fname='panda,' Where emp_id = 'A-C71970F'
   
   String sql;

   sql="insert into employee_new(emp_id,fname,lname,job_id,pub_id,hire_date) values(@emp_id,@fname,@lname,@job_id,@pub_id,@hire_date)";
   
   SqlConnection cn=new  SqlConnection("server=.;database=pubs;uid=sa;pwd=;");
   
   SqlCommand cmd=new SqlCommand(sql,cn);

   SqlParameter pmt;//表示 SqlCommand 的参数

   pmt=cmd.Parameters.Add("@emp_id",SqlDbType.Char,9);//添加参数,设置参数名称、类型、长度
   pmt.Value=TextBox1.Text;//设置参数值

   pmt=cmd.Parameters.Add("@fname",SqlDbType.VarChar,20);
   pmt.Value=TextBox2.Text;

   pmt=cmd.Parameters.Add("@lname",SqlDbType.VarChar,30);
   pmt.Value=TextBox3.Text;

   pmt=cmd.Parameters.Add("@job_id",SqlDbType.SmallInt,2);
   pmt.Value=TextBox4.Text;

   pmt=cmd.Parameters.Add("@pub_id",SqlDbType.Char,4);
   pmt.Value=TextBox5.Text;

   pmt=cmd.Parameters.Add("@hire_date",SqlDbType.DateTime,8);
   pmt.Value=TextBox6.Text;

   cn.Open();
   int Added;
   Added=cmd.ExecuteNonQuery();
   cn.Close();
   Label6.Text=Added.ToString();
   if (Added>0)
   {
    InitID();
    ShowData();
   }
  }

  private void Button7_Click(object sender, System.EventArgs e)
  {
   UpdateDataOK();
  }

  void UpdateDataOK()
  {
   String sql;
   
   sql="update employee_new set ";
   sql+="fname=@fname,";
   sql+="lname=@lname,";
   sql+="job_id=@job_id,";
   sql+="pub_id=@pub_id,";
   sql+="hire_date=@hire_date";
   sql+=" where emp_id=@emp_id";
   
   SqlConnection cn=new  SqlConnection("server=.;database=pubs;uid=sa;pwd=;");
   
   SqlCommand cmd=new SqlCommand(sql,cn);

   SqlParameter pmt;//表示 SqlCommand 的参数

   pmt=cmd.Parameters.Add("@emp_id",SqlDbType.Char,9);
   pmt.Value=TextBox1.Text;

   pmt=cmd.Parameters.Add("@fname",SqlDbType.VarChar,20);
   pmt.Value=TextBox2.Text;

   pmt=cmd.Parameters.Add("@lname",SqlDbType.VarChar,30);
   pmt.Value=TextBox3.Text;

   pmt=cmd.Parameters.Add("@job_id",SqlDbType.SmallInt,2);
   pmt.Value=TextBox4.Text;

   pmt=cmd.Parameters.Add("@pub_id",SqlDbType.Char,4);
   pmt.Value=TextBox5.Text;

   pmt=cmd.Parameters.Add("@hire_date",SqlDbType.DateTime,8);
   pmt.Value=TextBox6.Text;

   cn.Open();
   int Updated;
   Updated=cmd.ExecuteNonQuery();
   cn.Close();
   Label6.Text=Updated.ToString();
  }

  private void Button8_Click(object sender, System.EventArgs e)
  {
   DeleteDataOK();
  }

  void DeleteDataOK()
  {
   String sql="delete employee_new where emp_id=@emp_id";
   
   SqlConnection cn=new  SqlConnection("server=.;database=pubs;uid=sa;pwd=;");
   
   SqlCommand cmd=new SqlCommand(sql,cn);

   SqlParameter pmt;//表示 SqlCommand 的参数

   pmt=cmd.Parameters.Add("@emp_id",SqlDbType.Char,9);
   pmt.Value=TextBox1.Text;

   cn.Open();
   int Deleted;
   Deleted=cmd.ExecuteNonQuery();
   cn.Close();
   Label6.Text=Deleted.ToString();
   if (Deleted>0)
   {
    InitID();
    ShowData();
   }
  }
 }
}

 private void Page_Load(object sender, System.EventArgs e)
  {
   SqlConnection cn=new SqlConnection("server=.;database=pubs;uid=sa;pwd=");
   SqlCommand cmd=new SqlCommand();
   cmd.Connection=cn;
   SqlDataAdapter da=new SqlDataAdapter(cmd);
   DataSet ds=new DataSet();

   cmd.CommandText="select student,course,score from StudentScore";
   da.Fill(ds,"StudentScore");//所有记录

   cmd.CommandText="select distinct course from StudentScore";
   da.Fill(ds,"course");//课程名称

   cmd.CommandText="select distinct student from StudentScore";
   da.Fill(ds,"student");//学生名字

   DataTable od=new DataTable();//创建临时表重新排列数据
   DataColumn dcName=new DataColumn("student/course");
   od.Columns.Add(dcName);//新列:存放课程
   for(int i=0;i<ds.Tables["course"].Rows.Count;i++)
   {
    DataColumn dc=new DataColumn(ds.Tables["course"].Rows[i][0].ToString());
    od.Columns.Add(dc);//列名(课程名称)
   }

   for(int j=0;j<ds.Tables["student"].Rows.Count;j++)//对列(学生)进行循环
   {
    DataRow dw=od.NewRow();//分配一个新行空间
    dw[0]=ds.Tables["student"].Rows[j]["student"].ToString();//首列数据(学生名字)
    for(int k=0;k<ds.Tables["course"].Rows.Count;k++)//对其余列(每个课程一列)进行循环
    {
     DataRow[] dws2=ds.Tables["StudentScore"].Select("[student]='"+dw[0]+"' and course='"+ds.Tables["course"].Rows[k]["course"]+"'");
     //根据学生名称与其对应的课程进行查询
    }
    od.Rows.Add(dw);//将填充数据的行添加到临时表中
   }

   DataGrid1.DataSource=ds.Tables["StudentScore"];
   DataGrid1.DataBind();

   DataGrid2.DataSource=od;
   DataGrid2.DataBind();
  }


C#实现WEB服务器
[ 来源:xue5.com | 作者:原作者 | 时间:2005-5-14 ]

这只是一个简单的用C#写的WEB服务器,只实现了get方式的对html文件的请求,有兴趣的朋友可以在此基础之上继续开发更多功能,小弟学c#不久,如有错漏,望请见凉!!

摘要:

WWW的工作基于客户机/服务器计算模型,由Web 浏览器(客户机)和Web服务器(服务器)构成,两者之间采用超文本传送协议(HTTP)进行通信,HTTP协议的作用原理包括四个步骤:连接,请求,应答。根据上述HTTP协议的作用原理,本文实现了GET请求的Web服务器程序的方法,通过创建TcpListener类对象,监听端口8080; 等待、接受客户机连接到端口8080; 创建与socket字相关联的输入流和输出流;然后,读取客户机的请求信息,若请求类型是GET,则从请求信息中获取所访问的HTML文件名,如果HTML文件存在,则打开HTML文件,把HTTP头信息和HTML文件内容通过socket传回给Web浏览器,然后关闭文件。否则发送错误信息给Web浏览器。最后,关闭与相应Web浏览器连接的socket字。

一、HTTP协议的作用原理

WWW是以Internet作为传输媒介的一个应用系统,WWW网上最基本的传输单位是Web网页。WWW的工作基于客户机/服务器计算模型,由Web 浏览器(客户机)和Web服务器(服务器)构成,两者之间采用超文本传送协议(HTTP)进行通信。HTTP协议是基于TCP/IP协议之上的协议,是Web浏览器和Web服务器之间的应用层协议,是通用的、无状态的、面向对象的协议。HTTP协议的作用原理包括四个步骤:

连接:Web浏览器与Web服务器建立连接,打开一个称为socket(套接字)的虚拟文件,此文件的建立标志着连接建立成功。

请求:Web浏览器通过socket向Web服务器提交请求。HTTP的请求一般是GET或POST命令(POST用于FORM参数的传递)。GET命令的格式为:

GET 路径/文件名 HTTP/1.0

文件名指出所访问的文件,HTTP/1.0指出Web浏览器使用的HTTP版本。

应答:Web浏览器提交请求后,通过HTTP协议传送给Web服务器。Web服务器接到后,进行事务处理,处理结果又通过HTTP传回给Web浏览器,从而在Web浏览器上显示出所请求的页面。

例:假设客户机与www.mycomputer.com:8080/mydir/index.html建立了连接,就会发送GET命令:GET /mydir/index.html HTTP/1.0。主机名为http://www.mycomputer.com/的Web服务器从它的文档空间中搜索子目录mydir的文件index.html。如果找到该文件,Web服务器把该文件内容传送给相应的Web浏览器。

为了告知 Web浏览器传送内容的类型,Web服务器首先传送一些HTTP头信息,然后传送具体内容(即HTTP体信息),HTTP头信息和HTTP体信息之间用一个空行分开。

常用的HTTP头信息有:

① HTTP 1.0 200 OK

这是Web服务器应答的第一行,列出服务器正在运行的HTTP版本号和应答代码。代码“200 OK”表示请求完成。

② MIME_Version:1.0

它指示MIME类型的版本。

③ content_type:类型

这个头信息非常重要,它指示HTTP体信息的MIME类型。如:content_type:text/html指示传送的数据是HTML文档。

④ content_length:长度值

它指示HTTP体信息的长度(字节)。

关闭连接:当应答结束后,Web浏览器与Web服务器必须断开,以保证其它Web浏览器能够与Web服务器建立连接。

二、C#实现Web服务器功能的程序设计

根据上述HTTP协议的作用原理,实现GET请求的Web服务器程序的方法如下:

创建TcpListener类对象,监听某端口(任意输入闲置端口 如:8080 )。

等待、接受客户机连接到该端口,得到与客户机连接的socket;

从与socket关联的输入流中读取一行客户机提交的请求信息,请求信息的格式为:GET 路径/文件名 HTTP/1.0

从请求信息中获取请求类型。如果请求类型是GET,则从请求信息中获取所访问的HTML文件名。没有HTML文件名时,则以index.html作为文件名;

如果HTML文件存在,则打开HTML文件,把HTTP头信息和HTML文件内容通过socket传回给Web浏览器,然后关闭文件。否则发送错误信息给Web浏览器;

关闭与相应Web浏览器连接的socket字。


实现的代码如下:
//////////webserver.cs//////////////////


namespace cnnbsun.webserver
{
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 = 8080 ; // 选者任何闲置端口

//开始兼听端口
//同时启动一个兼听进程
public MyWebServer()
{
try
{
//开始兼听端口
myListener = new TcpListener(port) ;
myListener.Start();
Console.WriteLine("Web Server Running... Press ^C to Stop...");
//同时启动一个兼听进程 'StartListen'
Thread th = new Thread(new ThreadStart(StartListen));
th.Start() ;

}
catch(Exception e)
{
Console.WriteLine("兼听端口时发生错误 :" +e.ToString());
}
}
public void SendHeader(string sHttpVersion, string sMIMEHeader, int iTotBytes, string sStatusCode, ref Socket mySocket)
{

String sBuffer = "";

if (sMIMEHeader.Length == 0 )
{
sMIMEHeader = "text/html"; // 默认 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());

}

public void SendToBrowser(String sData, ref Socket mySocket)
{
SendToBrowser (Encoding.ASCII.GetBytes(sData), ref mySocket);
}

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("连接失败....");
}
catch (Exception e)
{
Console.WriteLine("发生错误 : {0} ", e );

}
}
public static void Main()
{
MyWebServer MWS = new MyWebServer();
}
public void StartListen()
{

int iStartPos = 0;
String sRequest;
String sDirName;
String sRequestedFile;
String sErrorMessage;
String sLocalDir;
/////////////////////////////////////注意设定你自己的虚拟目录/////////////////////////////////////
String sMyWebServerRoot = "E:\\MyWebServerRoot\\"; //设置你的虚拟目录
//////////////////////////////////////////////////////////////////////////////////////////////////
String sPhysicalFilePath = "";
String sFormattedMessage = "";
String sResponse = "";


while(true)
{
//接受新连接
Socket mySocket = myListener.AcceptSocket() ;

Console.WriteLine ("Socket Type " +mySocket.SocketType );
if(mySocket.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\nCLient IP {0}\n",mySocket.RemoteEndPoint) ;

Byte[] bReceive = new Byte[1024] ;
int i = mySocket.Receive(bReceive,bReceive.Length,0) ;


//转换成字符串类型
string sBuffer = Encoding.ASCII.GetString(bReceive);


//只处理"get"请求类型
if (sBuffer.Substring(0,3) != "GET" )
{
Console.WriteLine("只处理get请求类型..");
mySocket.Close();
return;
}

// 查找 "HTTP" 的位置
iStartPos = sBuffer.IndexOf("HTTP",1);


string sHttpVersion = sBuffer.Substring(iStartPos,8);


// 得到请求类型和文件目录文件名
sRequest = sBuffer.Substring(0,iStartPos - 1);

sRequest.Replace("file://","/");


//如果结尾不是文件名也不是以"/"结尾则加"/"
if ((sRequest.IndexOf(".") <1) && (!sRequest.EndsWith("/")))
{
sRequest = sRequest + "/";
}


//得带请求文件名
iStartPos = sRequest.LastIndexOf("/") + 1;
sRequestedFile = sRequest.Substring(iStartPos);


//得到请求文件目录
sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/")-3);


//获取虚拟目录物理路径
sLocalDir = sMyWebServerRoot;

Console.WriteLine("请求文件目录 : " + sLocalDir);

if (sLocalDir.Length == 0 )
{
sErrorMessage = "<H2>Error!! Requested Directory does not exists</H2><Br>";
SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found", ref mySocket);
SendToBrowser(sErrorMessage, ref mySocket);
mySocket.Close();
continue;
}


if (sRequestedFile.Length == 0 )
{
// 取得请求文件名
sRequestedFile = "index.html";
}


/////////////////////////////////////////////////////////////////////
// 取得请求文件类型(设定为text/html)
/////////////////////////////////////////////////////////////////////

String sMimeType = "text/html";

sPhysicalFilePath = sLocalDir + sRequestedFile;
Console.WriteLine("请求文件: " + 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);

BinaryReader reader = new BinaryReader(fs);
byte[] bytes = new byte[fs.Length];
int read;
while((read = reader.Read(bytes, 0, bytes.Length)) != 0)
{
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();
}
}
}


}

}

///////////结束////////////////

将文件编译成EXE文件,就实现了简单的WEB服务器功能!
可以设定一个虚拟目录,进行测试!
asp.net提供承载asp.net的方法。详细可以看这个例子: http://www.asp.net/Projects/Cassini/Download/Default.aspx?tabindex=0&tabid=1


posted on 2008-05-30 15:24  hekeneng  阅读(333)  评论(0编辑  收藏  举报

导航