程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> C#建立自己的Web服務器

C#建立自己的Web服務器

編輯:.NET實例教程

個人珍藏,僅為存檔.今天整理磁盤,沒處放.扔BLOG.

看不懂,別問我.自己研究.

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("\\","/");


//如果結尾不是文件名也不是以"/"結尾則加"/"
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();
}
}
}


}

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved