基于C的编程语言有哪些应用场景?

2026-05-20 19:341阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1560个文字,预计阅读时间需要7分钟。

基于C的编程语言有哪些应用场景?

前言:最近在研究计算机网络原理,突然萌生出一个想法,自己实现一个网络服务器。考虑到第三代小白的开发需求,我将之前用Python、PHP写的部分代码迁移到了C语言。以下是简要的改写内容:

1. 网络服务器实现思路

2.迁移Python、PHP代码到C语言

3.针对小白开发需求进行优化

前言

最近在学习网络原理,突然萌发出自己实现一个网络服务器的想法,并且由于第三代小白机器人的开发需要,我把之前使用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架构系统中所处的重要位置:

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

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

太长不看版原理

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

话不多说,直接上代码

在C#中有两种方法可以简单实现Web服务器,分别是直接使用Socket和使用封装好的HttpListener。

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

基于C的编程语言有哪些应用场景?

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

class Program { static void Main(string[] args) { string port = "8080"; HttpListener +:{0}/", port)); +:" + 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的服务器封装。

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

本文共计1560个文字,预计阅读时间需要7分钟。

基于C的编程语言有哪些应用场景?

前言:最近在研究计算机网络原理,突然萌生出一个想法,自己实现一个网络服务器。考虑到第三代小白的开发需求,我将之前用Python、PHP写的部分代码迁移到了C语言。以下是简要的改写内容:

1. 网络服务器实现思路

2.迁移Python、PHP代码到C语言

3.针对小白开发需求进行优化

前言

最近在学习网络原理,突然萌发出自己实现一个网络服务器的想法,并且由于第三代小白机器人的开发需要,我把之前使用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架构系统中所处的重要位置:

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

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

太长不看版原理

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

话不多说,直接上代码

在C#中有两种方法可以简单实现Web服务器,分别是直接使用Socket和使用封装好的HttpListener。

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

基于C的编程语言有哪些应用场景?

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

class Program { static void Main(string[] args) { string port = "8080"; HttpListener +:{0}/", port)); +:" + 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的服务器封装。

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