【.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);

            }

        }
AI 代码解读

核心代码就是对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();

                    }

                }

            }

        }
AI 代码解读

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);

        }
AI 代码解读

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);

            }

        }
AI 代码解读

好了,程序编写好后,直接部署到开发板上进行运行,连接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

目录
打赏
0
0
0
0
4751
分享
相关文章
|
2月前
|
基于 .NET 开发的多功能流媒体管理控制平台
基于 .NET 开发的多功能流媒体管理控制平台
57 9
一个.NET开源、免费、功能强大的 PDF 处理工具
一个.NET开源、免费、功能强大的 PDF 处理工具
3款.NET开源、功能强大的通讯调试工具,效率提升利器!
3款.NET开源、功能强大的通讯调试工具,效率提升利器!
63 10
一款基于 .NET MVC 框架开发、功能全面的MES系统
一款基于 .NET MVC 框架开发、功能全面的MES系统
【网络原理】——HTTP协议、fiddler抓包
HTTP超文本传输,HTML,fiddler抓包,URL,urlencode,HTTP首行方法,GET方法,POST方法
【网络原理】——HTTP请求头中的属性
HTTP请求头,HOST、Content-Agent、Content-Type、User-Agent、Referer、Cookie。
鸿蒙应用开发从入门到入行 - 篇7:http网络请求
在本篇文章里,您将掌握鸿蒙开发工具DevEco的基本使用、ArkUI里的基础组件,并通过制作一个简单界面掌握使用
92 8
HTTP代理IP纯净度 提升用户网络体验的核心竞争力
随着互联网发展,使用HTTP动态代理IP的需求日益增加。高纯净度的代理IP在隐私与安全、网络体验和业务运营方面至关重要。它能保护用户信息、提高数据安全性、确保访问速度和连接稳定,并提升业务效率与信誉度。
60 2
HTTP代理服务器在网络安全中的重要性
随着科技和互联网的发展,HTTP代理IP中的代理服务器在企业业务中扮演重要角色。其主要作用包括:保护用户信息、访问控制、缓存内容、负载均衡、日志记录和协议转换,从而在网络管理、性能优化和安全性方面发挥关键作用。
98 2
网络不稳定导致HTTP代理频繁掉线的分析
随着数字化时代的加速发展,网络安全、隐私保护及内容访问自由成为用户核心需求。HTTP代理服务器因其独特技术优势受到青睐,但其掉线问题频发。本文分析了HTTP代理服务器不稳定导致掉线的主要原因,包括网络问题、服务器质量、用户配置错误及IP资源问题等方面。
157 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等