您好,登錄后才能下訂單哦!
這篇文章主要講解了“C#怎么實(shí)現(xiàn)Web服務(wù)器功能”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“C#怎么實(shí)現(xiàn)Web服務(wù)器功能”吧!
C#實(shí)現(xiàn)Web服務(wù)器功能的程序設(shè)計(jì)
根據(jù)HTTP協(xié)議的作用原理,實(shí)現(xiàn)GET請求的Web服務(wù)器程序的方法如下:
創(chuàng)建TcpListener類對象,監(jiān)聽某端口(任意輸入閑置端口 如:8080 )。等待、接受客戶機(jī)連接到該端口,得到與客戶機(jī)連接的socket;從與socket關(guān)聯(lián)的輸入流中讀取一行客戶機(jī)提交的請求信息,請求信息的格式為:GET 路徑/文件名 HTTP/1.0。從請求信息中獲取請求類型。如果請求類型是GET,則從請求信息中獲取所訪問的HTML文件名。沒有HTML文件名時(shí),則以index.html作為文件名;
如果HTML文件存在,則打開HTML文件,把HTTP頭信息和HTML文件內(nèi)容通過socket傳回給Web瀏覽器,然后關(guān)閉文件。否則發(fā)送錯(cuò)誤信息給Web瀏覽器;關(guān)閉與相應(yīng)Web瀏覽器連接的socket字。
C#實(shí)現(xiàn)Web服務(wù)器功能的代碼如下:
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 ; // 選者任何閑置端口
//開始兼聽端口
//同時(shí)啟動(dòng)一個(gè)兼聽進(jìn)程
public MyWebServer()
{
try
{
//開始兼聽端口
myListener = new TcpListener(port) ;
myListener.Start();
Console.WriteLine("Web Server Running... Press ^C to Stop...");
//同時(shí)啟動(dòng)一個(gè)兼聽進(jìn)程 ''StartListen''
Thread th = new Thread(new ThreadStart(StartListen));
th.Start() ;
}
catch(Exception e)
{
Console.WriteLine("兼聽端口時(shí)發(fā)生錯(cuò)誤 :" +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"; // 默認(rèn) text/html
}
sBuffersBuffer = sBuffer + sHttpVersion + sStatusCode + "\r\n";
sBuffersBuffer = sBuffer + "Server: cx1193719-b\r\n";
sBuffersBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";
sBuffersBuffer = sBuffer + "Accept-Ranges: bytes\r\n";
sBuffersBuffer = 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("發(fā)生錯(cuò)誤 : {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\\"; //設(shè)置你的虛擬目錄
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) ;
//轉(zhuǎn)換成字符串類型
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("\\","/");
//如果結(jié)尾不是文件名也不是以"/"結(jié)尾則加"/"
if ((sRequest.IndexOf(".") <1) && (!sRequest.EndsWith("/")))
{
sRequestsRequest = sRequest + "/";
}
//得帶請求文件名
iStartPos = sRequest.LastIndexOf("/") + 1;
sRequestsRequestedFile = 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";
}
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)
{
sResponsesResponse = sResponse + Encoding.ASCII.GetString(bytes,0,read);
iTotBytesiTotBytes = 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();
}
}
}
}
}
感謝各位的閱讀,以上就是“C#怎么實(shí)現(xiàn)Web服務(wù)器功能”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對C#怎么實(shí)現(xiàn)Web服務(wù)器功能這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。