欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于C#动手实现网络服务器Web Server

程序员文章站 2023-12-13 10:18:52
前言 最近在学习网络原理,突然萌发出自己实现一个网络服务器的想法,并且由于第三代小白机器人的开发需要,我把之前使用python、php写的那部分代码都迁移到了c#(别...

前言

最近在学习网络原理,突然萌发出自己实现一个网络服务器的想法,并且由于第三代小白机器人的开发需要,我把之前使用python、php写的那部分代码都迁移到了c#(别问我为什么这么喜欢c#),之前使用php就是用来处理网络请求的,现在迁移到c#了,而linux系统上并没有iis服务器,自然不能使用asp.net,所以这个时候自己实现一个功能简单的网络服务器就恰到好处地解决这些问题了。

基本原理

web server在一个b/s架构系统中起到的作用不仅多而且相当重要,web开发者大部分时候并不需要了解它的详细工作机制。虽然不同的web server可能功能并不完全一样,但是以下三个功能几乎是所有web server必须具备的:

接收来自浏览器端的http请求
将请求转发给指定web站点程序(后者由web开发者编写,负责处理请求)
向浏览器发送请求处理结果

下图显示web server在整个web架构系统中所处的重要位置:

基于C#动手实现网络服务器Web Server

如上图,web server起到了一个“承上启下”的作用(虽然并没有“上下”之分),它负责连接用户和web站点。

每个网站就像一个个“插件”,只要网站开发过程中遵循了web server提出的规则,那么该网站就可以“插”在web server上,我们便可以通过浏览器访问网站。

太长不看版原理

浏览器想要拿到哪个文件(html、css、js、image)就和服务器发请求信息说我要这个文件,然后服务器检查请求合不合法,如果合法就把文件数据传回给浏览器,这样浏览器就可以把网站显示出来了。(一个网站一般会包含n多个文件)

话不多说,直接上代码

在c#中有两种方法可以简单实现web服务器,分别是直接使用socket和使用封装好的httplistener。

因为后者比较方便一些,所以我选择使用后者。

这是最简单的实现一个网络服务器,可以处理浏览器发过来的请求,然后将指定的字符串内容返回。

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("监听端口:" + port);
    console.read();
  }

  static void getcontext(iasyncresult ar)
  {
    httplistener httplistener = ar.asyncstate as httplistener;
    httplistenercontext context = httplistener.endgetcontext(ar); //接收到的请求context(一个环境封装体)

    httplistener.begingetcontext(new asynccallback(getcontext), httplistener); //开始 第二次 异步接收request请求

    httplistenerrequest request = context.request; //接收的request数据
    httplistenerresponse response = context.response; //用来向客户端发送回复

    response.contenttype = "html";
    response.contentencoding = encoding.utf8;

    using (stream output = response.outputstream) //发送回复
    {
      byte[] buffer = encoding.utf8.getbytes("要返回的内容");
      output.write(buffer, 0, buffer.length);
    }
  }
}

这个简单的代码已经可以实现用于小白机器人的网络请求处理了,因为大致只用到get和post两种http方法,只需要在getcontext方法里判断get、post方法,然后分别给出响应就可以了。

但是我们的目的是开发一个真正的网络服务器,当然不能只满足于这样一个专用的服务器,我们要的是可以提供网页服务的服务器。

那就继续吧。

根据我的研究,提供网页访问服务的服务器做起来确实有一点麻烦,因为需要处理的东西很多。需要根据浏览器请求的不同文件给出不同响应,处理cookies,还要处理编码,还有各种出错的处理。

首先我们要确定一下我们的服务器要提供哪些文件的访问服务。

这里我用一个字典结构来保存。

/// <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接入的方式使我们的服务器支持php。

我在qframework中封装了一个qhttpwebserver模块,这是其中的启动代码。

/// <summary>
/// 启动本地网页服务器
/// </summary>
/// <param name="webroot">网站根目录</param>
/// <returns></returns>
public bool start(string webroot)
{
  //触发事件
  if (onserverstart != null)
  onserverstart(httplistener);

  webroot = webroot;
  try
  {
    //监听端口
    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;
}

现在把网页服务器的核心处理代码贴出来。

这个代码只是做了基本的处理,对于网站的主页只做了html后缀的识别。

后来我在qframework中封装的模块做了更多的细节处理。

/// <summary>
/// 网页服务器相应处理
/// </summary>
/// <param name="ar"></param>
private void onwebresponse(iasyncresult ar)
{
  byte[] responsebyte = null;  //响应数据

  httplistener httplistener = ar.asyncstate as httplistener;
  httplistenercontext context = httplistener.endgetcontext(ar); //接收到的请求context(一个环境封装体)      

  httplistener.begingetcontext(new asynccallback(onwebresponse), httplistener); //开始 第二次 异步接收request请求

  //触发事件
  if (ongetrawcontext != null)
    ongetrawcontext(context);

  httplistenerrequest request = context.request; //接收的request数据
  httplistenerresponse response = context.response; //用来向客户端发送回复

  //触发事件
  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) //发送回复
  {
    try
    {
      output.write(responsebyte, 0, responsebyte.length);
    }
    catch (exception ex)
    {
      qdb.error(ex.message, qdebugerrortype.error, "onwebresponse");
      response.statuscode = (int)httpstatuscode.internalservererror;
    }
  }
}

这样就可以提供基本的网页访问了,经过测试,使用bootstrap,pure等前端框架的网页都可以完美访问,性能方面一般般。(在qframework的封装中我做了一点性能优化,有一点提升)我觉得要在性能方面做提升还是要在多线程处理这方面做优化,由于篇幅关系,就不把多线程版本的代码贴出来了。

接下来我们还要实现服务器的php支持。

首先定义两个字段。

/// <summary>
/// 是否开启php功能
/// </summary>
public bool php_cgi_enabled = true;

/// <summary>
/// php执行文件路径
/// </summary>
public string php_cgi_path = "php-cgi";
接下来在网页服务的核心代码里做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; //是否指定操作系统外壳进程启动程序
    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;
    }
  }
}

这样就实现了基于php-cgi的php支持了,经过测试,基本的php页面都可以支持,但是需要使用curl和xml这类扩展的暂时还没办法。需要做更多的工作。

接下来我会给服务器做一个gui界面,供大家测试。

同时也会把qframework框架发布,有兴趣的可以使用基于qframework的服务器封装。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: