C#實現簡單WEB伺服器

來源:互聯網
上載者:User
一、HTTP協議的作用原理

WWW是以Internet作為傳輸媒介的一個應用系統,WWW網上最基本的傳輸單位是Web網頁。WWW的工作基於客戶機/伺服器計算模型,由網頁瀏覽器(客戶機)和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。主機名稱為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("\\","/");

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

}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.