溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

基于C#動手實現(xiàn)網(wǎng)絡(luò)服務(wù)器Web Server

發(fā)布時間:2020-08-25 15:18:10 來源:腳本之家 閱讀:185 作者:Deali-Axy 欄目:編程語言

前言

最近在學(xué)習(xí)網(wǎng)絡(luò)原理,突然萌發(fā)出自己實現(xiàn)一個網(wǎng)絡(luò)服務(wù)器的想法,并且由于第三代小白機器人的開發(fā)需要,我把之前使用python、PHP寫的那部分代碼都遷移到了C#(別問我為什么這么喜歡C#),之前使用PHP就是用來處理網(wǎng)絡(luò)請求的,現(xiàn)在遷移到C#了,而Linux系統(tǒng)上并沒有IIS服務(wù)器,自然不能使用ASP.Net,所以這個時候自己實現(xiàn)一個功能簡單的網(wǎng)絡(luò)服務(wù)器就恰到好處地解決這些問題了。

基本原理

Web Server在一個B/S架構(gòu)系統(tǒng)中起到的作用不僅多而且相當(dāng)重要,Web開發(fā)者大部分時候并不需要了解它的詳細工作機制。雖然不同的Web Server可能功能并不完全一樣,但是以下三個功能幾乎是所有Web Server必須具備的:

接收來自瀏覽器端的HTTP請求
將請求轉(zhuǎn)發(fā)給指定Web站點程序(后者由Web開發(fā)者編寫,負責(zé)處理請求)
向瀏覽器發(fā)送請求處理結(jié)果

下圖顯示W(wǎng)eb Server在整個Web架構(gòu)系統(tǒng)中所處的重要位置:

基于C#動手實現(xiàn)網(wǎng)絡(luò)服務(wù)器Web Server

如上圖,Web Server起到了一個“承上啟下”的作用(雖然并沒有“上下”之分),它負責(zé)連接用戶和Web站點。

每個網(wǎng)站就像一個個“插件”,只要網(wǎng)站開發(fā)過程中遵循了Web Server提出的規(guī)則,那么該網(wǎng)站就可以“插”在Web Server上,我們便可以通過瀏覽器訪問網(wǎng)站。

太長不看版原理

瀏覽器想要拿到哪個文件(html、css、js、image)就和服務(wù)器發(fā)請求信息說我要這個文件,然后服務(wù)器檢查請求合不合法,如果合法就把文件數(shù)據(jù)傳回給瀏覽器,這樣瀏覽器就可以把網(wǎng)站顯示出來了。(一個網(wǎng)站一般會包含n多個文件)

話不多說,直接上代碼

在C#中有兩種方法可以簡單實現(xiàn)Web服務(wù)器,分別是直接使用Socket和使用封裝好的HttpListener。

因為后者比較方便一些,所以我選擇使用后者。

這是最簡單的實現(xiàn)一個網(wǎng)絡(luò)服務(wù)器,可以處理瀏覽器發(fā)過來的請求,然后將指定的字符串內(nèi)容返回。

class Program
{
  static void Main(string[] args)
  {
    string port = "8080";
    HttpListener httpListener = new HttpListener();
    httpListener.Prefixes.Add(string.Format("http://+:{0}/", port));
    httpListener.Start();
    httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener); //開始異步接收request請求
    Console.WriteLine("監(jiān)聽端口:" + port);
    Console.Read();
  }

  static void GetContext(IAsyncResult ar)
  {
    HttpListener httpListener = ar.AsyncState as HttpListener;
    HttpListenerContext context = httpListener.EndGetContext(ar); //接收到的請求context(一個環(huán)境封裝體)

    httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener); //開始 第二次 異步接收request請求

    HttpListenerRequest request = context.Request; //接收的request數(shù)據(jù)
    HttpListenerResponse response = context.Response; //用來向客戶端發(fā)送回復(fù)

    response.ContentType = "html";
    response.ContentEncoding = Encoding.UTF8;

    using (Stream output = response.OutputStream) //發(fā)送回復(fù)
    {
      byte[] buffer = Encoding.UTF8.GetBytes("要返回的內(nèi)容");
      output.Write(buffer, 0, buffer.Length);
    }
  }
}

這個簡單的代碼已經(jīng)可以實現(xiàn)用于小白機器人的網(wǎng)絡(luò)請求處理了,因為大致只用到GET和POST兩種HTTP方法,只需要在GetContext方法里判斷GET、POST方法,然后分別給出響應(yīng)就可以了。

但是我們的目的是開發(fā)一個真正的網(wǎng)絡(luò)服務(wù)器,當(dāng)然不能只滿足于這樣一個專用的服務(wù)器,我們要的是可以提供網(wǎng)頁服務(wù)的服務(wù)器。

那就繼續(xù)吧。

根據(jù)我的研究,提供網(wǎng)頁訪問服務(wù)的服務(wù)器做起來確實有一點麻煩,因為需要處理的東西很多。需要根據(jù)瀏覽器請求的不同文件給出不同響應(yīng),處理Cookies,還要處理編碼,還有各種出錯的處理。

首先我們要確定一下我們的服務(wù)器要提供哪些文件的訪問服務(wù)。

這里我用一個字典結(jié)構(gòu)來保存。

/// <summary>
/// MIME類型
/// </summary>
public Dictionary<string, string> MIME_Type = new Dictionary<string, string>()
{
  { "htm", "text/html" },
  { "html", "text/html" },
  { "php", "text/html" },
  { "xml", "text/xml" },
  { "json", "application/json" },
  { "txt", "text/plain" },
  { "js", "application/x-javascript" },
  { "css", "text/css" },
  { "bmp", "image/bmp" },
  { "ico", "image/ico" },
  { "png", "image/png" },
  { "gif", "image/gif" },
  { "jpg", "image/jpeg" },
  { "jpeg", "image/jpeg" },
  { "webp", "image/webp" },
  { "zip", "application/zip"},
  { "*", "*/*" }
};

劇透一下:其中有PHP類型是我們后面要使用CGI接入的方式使我們的服務(wù)器支持PHP。

我在QFramework中封裝了一個QHttpWebServer模塊,這是其中的啟動代碼。

/// <summary>
/// 啟動本地網(wǎng)頁服務(wù)器
/// </summary>
/// <param name="webroot">網(wǎng)站根目錄</param>
/// <returns></returns>
public bool Start(string webroot)
{
  //觸發(fā)事件
  if (OnServerStart != null)
  OnServerStart(httpListener);

  WebRoot = webroot;
  try
  {
    //監(jiān)聽端口
    httpListener.Prefixes.Add("http://+:" + port.ToString() + "/");
    httpListener.Start();
    httpListener.BeginGetContext(new AsyncCallback(onWebResponse), httpListener); //開始異步接收request請求
  }
  catch (Exception ex)
  {
    Qdb.Error(ex.Message, QDebugErrorType.Error, "Start");
    return false;
  }
  return true;
}

現(xiàn)在把網(wǎng)頁服務(wù)器的核心處理代碼貼出來。

這個代碼只是做了基本的處理,對于網(wǎng)站的主頁只做了html后綴的識別。

后來我在QFramework中封裝的模塊做了更多的細節(jié)處理。

/// <summary>
/// 網(wǎng)頁服務(wù)器相應(yīng)處理
/// </summary>
/// <param name="ar"></param>
private void onWebResponse(IAsyncResult ar)
{
  byte[] responseByte = null;  //響應(yīng)數(shù)據(jù)

  HttpListener httpListener = ar.AsyncState as HttpListener;
  HttpListenerContext context = httpListener.EndGetContext(ar); //接收到的請求context(一個環(huán)境封裝體)      

  httpListener.BeginGetContext(new AsyncCallback(onWebResponse), httpListener); //開始 第二次 異步接收request請求

  //觸發(fā)事件
  if (OnGetRawContext != null)
    OnGetRawContext(context);

  HttpListenerRequest request = context.Request; //接收的request數(shù)據(jù)
  HttpListenerResponse response = context.Response; //用來向客戶端發(fā)送回復(fù)

  //觸發(fā)事件
  if (OnGetRequest != null)
    OnGetRequest(request, response);

  if (rawUrl == "" || rawUrl == "/") //單純輸入域名或主機IP地址
    fileName = WebRoot + @"\index.html";
  else if (rawUrl.IndexOf('.') == -1) //不帶擴展名,理解為文件夾
    fileName = WebRoot + @"\" + rawUrl.SubString(1) + @"\index.html";
  else
  {
    int fileNameEnd = rawUrl.IndexOf('?');
    if (fileNameEnd > -1)
      fileName = rawUrl.Substring(1, fileNameEnd - 1);
    fileName = WebRoot + @"\" + rawUrl.Substring(1);
  }

  //處理請求文件名的后綴
  string fileExt = Path.GetExtension(fileName).Substring(1);

  if (!File.Exists(fileName))
  {
    responseByte = Encoding.UTF8.GetBytes("404 Not Found!");
    response.StatusCode = (int)HttpStatusCode.NotFound;
  }
  else
  {
    try
    {
      responseByte = File.ReadAllBytes(fileName);
      response.StatusCode = (int)HttpStatusCode.OK;
    }
    catch (Exception ex)
    {
      Qdb.Error(ex.Message, QDebugErrorType.Error, "onWebResponse");
      response.StatusCode = (int)HttpStatusCode.InternalServerError;
    }
  }

  if (MIME_Type.ContainsKey(fileExt))
    response.ContentType = MIME_Type[fileExt];
  else
    response.ContentType = MIME_Type["*"];

  response.Cookies = request.Cookies; //處理Cookies

  response.ContentEncoding = Encoding.UTF8;

  using (Stream output = response.OutputStream) //發(fā)送回復(fù)
  {
    try
    {
      output.Write(responseByte, 0, responseByte.Length);
    }
    catch (Exception ex)
    {
      Qdb.Error(ex.Message, QDebugErrorType.Error, "onWebResponse");
      response.StatusCode = (int)HttpStatusCode.InternalServerError;
    }
  }
}

這樣就可以提供基本的網(wǎng)頁訪問了,經(jīng)過測試,使用Bootstrap,Pure等前端框架的網(wǎng)頁都可以完美訪問,性能方面一般般。(在QFramework的封裝中我做了一點性能優(yōu)化,有一點提升)我覺得要在性能方面做提升還是要在多線程處理這方面做優(yōu)化,由于篇幅關(guān)系,就不把多線程版本的代碼貼出來了。

接下來我們還要實現(xiàn)服務(wù)器的PHP支持。

首先定義兩個字段。

/// <summary>
/// 是否開啟PHP功能
/// </summary>
public bool PHP_CGI_Enabled = true;

/// <summary>
/// PHP執(zhí)行文件路徑
/// </summary>
public string PHP_CGI_Path = "php-cgi";
接下來在網(wǎng)頁服務(wù)的核心代碼里做PHP支持的處理。

//PHP處理
string phpCgiOutput = "";
Action phpProc = new Action(() =>
{
  try
  {
    string argStr = "";

    if (request.HttpMethod == "GET")
    {
      if (rawUrl.IndexOf('?') > -1)
        argStr = rawUrl.Substring(rawUrl.IndexOf('?'));
    }
    else if (request.HttpMethod == "POST")
    {
      using (StreamReader reader = new StreamReader(request.InputStream))
      {
        argStr = reader.ReadToEnd();
      }
    }

    Process p = new Process();
    p.StartInfo.CreateNoWindow = false; //不顯示窗口
    p.StartInfo.RedirectStandardOutput = true; //重定向輸出
    p.StartInfo.RedirectStandardInput = false; //重定向輸入
    p.StartInfo.UseShellExecute = false; //是否指定操作系統(tǒng)外殼進程啟動程序
    p.StartInfo.FileName = PHP_CGI_Path;
    p.StartInfo.Arguments = string.Format("-q -f {0} {1}", fileName, argStr);
    p.Start();

    StreamReader sr = p.StandardOutput;
    while (!sr.EndOfStream)
    {
      phpCgiOutput += sr.ReadLine() + Environment.NewLine;
    }

    responseByte = sr.CurrentEncoding.GetBytes(phpCgiOutput);
  }
  catch (Exception ex)
  {
    Qdb.Error(ex.Message, QDebugErrorType.Error, "onWebResponse->phpProc");
    response.StatusCode = (int)HttpStatusCode.InternalServerError;
  }
});

if (fileExt == "php" && PHP_CGI_Enabled)
{
  phpProc();
}
else
{
  if (!File.Exists(fileName))
  {
    responseByte = Encoding.UTF8.GetBytes("404 Not Found!");
    response.StatusCode = (int)HttpStatusCode.NotFound;
  }
  else
  {
    try
    {
      responseByte = File.ReadAllBytes(fileName);
      response.StatusCode = (int)HttpStatusCode.OK;
    }
    catch (Exception ex)
    {
      Qdb.Error(ex.Message, QDebugErrorType.Error, "onWebResponse");
      response.StatusCode = (int)HttpStatusCode.InternalServerError;
    }
  }
}

這樣就實現(xiàn)了基于PHP-CGI的PHP支持了,經(jīng)過測試,基本的php頁面都可以支持,但是需要使用curl和xml這類擴展的暫時還沒辦法。需要做更多的工作。

接下來我會給服務(wù)器做一個GUI界面,供大家測試。

同時也會把QFramework框架發(fā)布,有興趣的可以使用基于QFramework的服務(wù)器封裝。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI