【.Net MF网络开发板研究-02】Http Server功能演示

简介: 文章介绍的是真正的Http Server,支持GET和POST功能。同样我们还是在官方示例Http Server上进行修改,为了使示例更清晰,我们尽可能把代码做的更简单一些。

在上一篇博文中介绍的Web Server,其实是Socket编程应用,我们这篇文章介绍的是真正的Http Server,支持GET和POST功能。

同样我们还是在官方示例Http Server上进行修改,为了使示例更清晰,我们尽可能把代码做的更简单一些。

主程序直接修改为如下代码:

        public static void Main()

        {

            try

            {

                RunServer("http");

            }

            catch (Exception e)

            {

                Debug.Print(e.Message);

            }

        }

核心代码就是对GET和POST请求的支持,这里我们不要变,代码如下:

internal static void RunServer(string prefix)

     {

            HttpListener listener = new HttpListener(prefix, -1);                    

            listener.Start();

            while (true)

            {

                HttpListenerResponse response = null;

                HttpListenerContext context = null;

                try

                {

                    context = listener.GetContext();

                    response = context.Response;

                    HttpListenerRequest request = context.Request;

                    switch (request.HttpMethod.ToUpper())

                    {

                        case "GET":  GetRequest(context);  break;

                        case "POST": PostRequest(context); break;

                    }

                    if (response != null)

                    {

                        response.Close();

                    }

                }

                catch

                {

                    if (context != null)

                    {

                        context.Close();

                    }

                }

            }

        }

GET 请求处理代码如下,我们进行了大幅度的简化和调整,并且增加了一个upload.asp处理模块,代码如下:

   private static void GetRequest(HttpListenerContext context)

        {

            HttpListenerRequest request = context.Request;

            HttpListenerResponse response = context.Response;

            string strFilePath = GetPathFromURL(request.RawUrl);

            Debug.Print(strFilePath);

            response.StatusCode = (int)HttpStatusCode.OK;

            // Start HTML document

            string strResp = "<HTML><BODY>.Net Micro Framework Example HTTP Server<p>";

            // Print requested verb, URL and version.. Adds information from the request.

            strResp += "HTTP Method: " + request.HttpMethod + "<br> Requested URL: \"" + request.RawUrl +

                "\"<br> HTTP Version: " + request.ProtocolVersion + "\"<p>";        

 

            if (strFilePath.ToLower() == "\\upload.asp")

            {

                strResp += Resource1.GetString(Resource1.StringResources.PostForm);

            }

            else

            {

                strResp += "File to access " + strFilePath + "<p>";

                strResp += "Directory: \"" + strFilePath + "\" Does not exists";

            }

            // Closes HTML

            strResp += "</BODY></HTML>";

            // Sends it.

            byte[] messageBody = Encoding.UTF8.GetBytes(strResp);

            response.ContentType = "text/html";

            response.OutputStream.Write(messageBody, 0, messageBody.Length);

        }

POST处理部分,我们也进行了简化,不过变化不大,相关代码如下:

  private static void PostRequest(HttpListenerContext context)

        {

            // Retrieves request and response.

            HttpListenerRequest request = context.Request;

            HttpListenerResponse response = context.Response;

 

            // Allocates buffer for reading of message body

            byte[] postdata = new byte[BUFFER_SIZE];

 

            // Now reads the posted data. The content length should be supplied.

            // It is error not to have content length with post request.

            if (request.ContentLength64 > 0)

            {

                Debug.Print("Request Headers:");

                Debug.Print(request.Headers.ToString());

 

                long totalBytesReceived = 0;

                long contLen = request.ContentLength64;

                while (totalBytesReceived < contLen)

                {

                    int bytesToRead = (int)(contLen - totalBytesReceived);

                    // Limit to buffer size

                    bytesToRead = bytesToRead < BUFFER_SIZE ? bytesToRead : BUFFER_SIZE;

 

                    int dataRead = request.InputStream.Read(postdata, 0, bytesToRead);

                    if (dataRead == 0)

                    {

                        // Definitely some error. Means file incomplete.

                        break;

                    }      

                    totalBytesReceived += dataRead;

                };

               

                // Sends response:

                string strResp = "<HTML><BODY>.Net Micro Framework Example HTTP Server<p>";

                // Print requested verb, URL and version.. Adds information from the request.

                strResp += "HTTP Method: " + request.HttpMethod + "<br> Requested URL: \"" + request.RawUrl +

                    "\"<br> HTTP Version: " + request.ProtocolVersion + "\"<p>";

                strResp += "Amount of data received in message body: " + totalBytesReceived + "<br>";

                strResp += "Data of message body is discarded (if there is no filesystem). Please review HTTP Server sample code to add processing of data";

                strResp += "</BODY></HTML>";

                response.StatusCode = (int)HttpStatusCode.OK;

                byte[] messageBody = Encoding.UTF8.GetBytes(strResp);

                response.ContentType = "text/html";

                response.OutputStream.Write(messageBody, 0, messageBody.Length);

            }

            else // Content length is missing, send error back

            {

                // Sends response:

                string strResp = "<HTML><BODY>Content length is missing in Post request</BODY></HTML>";

                byte[] messageBody = Encoding.UTF8.GetBytes(strResp);

                response.ContentType = "text/html";

                response.OutputStream.Write(messageBody, 0, messageBody.Length);

            }

        }

好了,程序编写好后,直接部署到开发板上进行运行,连接PC,打开IE 浏览器,输入http://192.168.0.100/a.txt,效果如下:
image.png

本意是如果存在a.txt文件,则下载a.txt的内容,不过我们在代码中没有处理。

下面演示一下POST的使用,在IE浏览器中输入:http://192.168.0.100/Upload.asp

IE显示的内容如下:
image.png

我们随意选择一个文件,然后单击 【Send File Data To Server】按钮,则Http Server处理POST请求,并返回,IE此时会新弹出一个页面,如下图:
image.png

在Http Server 的POST处理程序内,我们可以获取上传文件的内容,这里我们没有显示相关内容,只是显示了它的大小,如611个字节。

.NET Micro Framework支持的网络功能还很多,如对WCF的支持,有待我们今后细细研究。

 -----------------------------------------------------------------------------------------------------------------------

源码/文档:http://www.sky-walker.com.cn/MFRelease/Sample/YFHttpServer.rar

MF论坛:http://space.cnblogs.com/group/MFSoft/

MF开发板:http://item.taobao.com/item.htm?id=7117999726

网络开发板:http://item.taobao.com/item.htm?id=10919470266

相关文章
|
25天前
|
存储 网络协议 算法
从HPACK到多路复用,揭秘HTTP/2如何终结网络拥堵
HTTP/2通过HPACK压缩头部冗余信息,提升传输效率;并利用多路复用技术,在单个TCP连接上并行处理多个请求,避免队头阻塞,显著提升性能。同时支持服务器推送和流优先级设置,优化资源加载体验。
87 7
|
24天前
|
安全 网络性能优化 网络虚拟化
网络交换机分类与功能解析
接入交换机(ASW)连接终端设备,提供高密度端口与基础安全策略;二层交换机(LSW)基于MAC地址转发数据,构成局域网基础;汇聚交换机(DSW)聚合流量并实施VLAN路由、QoS等高级策略;核心交换机(CSW)作为网络骨干,具备高性能、高可靠性的高速转发能力;中间交换机(ISW)可指汇聚层设备或刀片服务器内交换模块。典型流量路径为:终端→ASW→DSW/ISW→CSW,分层架构提升网络扩展性与管理效率。(238字)
398 0
|
4月前
|
JSON 中间件 Go
Go 网络编程:HTTP服务与客户端开发
Go 语言的 `net/http` 包功能强大,可快速构建高并发 HTTP 服务。本文从创建简单 HTTP 服务入手,逐步讲解请求与响应对象、URL 参数处理、自定义路由、JSON 接口、静态文件服务、中间件编写及 HTTPS 配置等内容。通过示例代码展示如何使用 `http.HandleFunc`、`http.ServeMux`、`http.Client` 等工具实现常见功能,帮助开发者掌握构建高效 Web 应用的核心技能。
257 61
|
7月前
|
Shell 网络安全 C#
一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
206 4
|
5月前
|
缓存 开发框架 .NET
一个功能丰富的 .NET 工具库 XiHan.Framework.Utils
XiHan.Framework.Utils 是一个功能全面的 .NET 工具库,包含字符串处理、集合扩展、加密解密、分布式 ID、文件操作、缓存、线程、国际化等模块。设计上注重高内聚、低耦合,适用于各类 .NET 应用开发。支持 AES 加密、树形结构转换、分页过滤、日志输出等功能,提供简单易用的 API。可通过 NuGet 快速安装,源码开放,采用 MIT 协议。
198 56
|
4月前
|
JSON 编解码 API
Go语言网络编程:使用 net/http 构建 RESTful API
本章介绍如何使用 Go 语言的 `net/http` 标准库构建 RESTful API。内容涵盖 RESTful API 的基本概念及规范,包括 GET、POST、PUT 和 DELETE 方法的实现。通过定义用户数据结构和模拟数据库,逐步实现获取用户列表、创建用户、更新用户、删除用户的 HTTP 路由处理函数。同时提供辅助函数用于路径参数解析,并展示如何设置路由器启动服务。最后通过 curl 或 Postman 测试接口功能。章节总结了路由分发、JSON 编解码、方法区分、并发安全管理和路径参数解析等关键点,为更复杂需求推荐第三方框架如 Gin、Echo 和 Chi。
|
5月前
|
安全 网络协议 Linux
Linux网络应用层协议展示:HTTP与HTTPS
此外,必须注意,从HTTP迁移到HTTPS是一项重要且必要的任务,因为这不仅关乎用户信息的安全,也有利于你的网站评级和粉丝的信心。在网络世界中,信息的安全就是一切,选择HTTPS,让您的网站更加安全,使您的用户满意,也使您感到满意。
151 18
|
6月前
|
安全 网络安全 定位技术
网络通讯技术:HTTP POST协议用于发送本地压缩数据到服务器的方案。
总的来说,无论你是一名网络开发者,还是普通的IT工作人员,理解并掌握POST方法的运用是非常有价值的。它就像一艘快速,稳定,安全的大船,始终为我们在网络海洋中的冒险提供了可靠的支持。
197 22
|
6月前
|
网络安全
网络问题解析:如何解决CondaHTTPError HTTP 000 CONNECTION FAILED错误。
以上就是斯诺普为你准备的解决Conda出现HTTP连接错误的手术室。希望这辆小车可以顺利驶出棘手的泥潭,再次在自由的大路上疾驰。一切的尝试和努力,只为更好的探索与开发。
224 17
|
8月前
|
人工智能 机器人
D1net阅闻 | 谷歌DeepMind研究发现LLM新特性
D1net阅闻 | 谷歌DeepMind研究发现LLM新特性