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

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

在上一篇博文中介绍的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,效果如下:

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

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

IE显示的内容如下:

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

在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

QQ群:127465602(已满) 146524112

1.png

相关文章
|
15天前
|
存储 文字识别 C#
.NET开源免费、功能强大的 Windows 截图录屏神器
今天大姚给大家分享一款.NET开源免费(基于GPL3.0开源协议)、功能强大、简洁灵活的 Windows 截图、录屏、Gif动图制作神器:ShareX。
|
3月前
|
域名解析 缓存 Linux
如何让你的.NET WebAPI程序支持HTTP3?
如何让你的.NET WebAPI程序支持HTTP3?
47 2
如何让你的.NET WebAPI程序支持HTTP3?
|
3月前
|
应用服务中间件 nginx
百度搜索:蓝易云【HTTP请求是如何关联Nginx server{}块的?】
总结来说,Nginx中的 `server{}`块用于关联HTTP请求和虚拟主机,通过配置不同的 `server{}`块,可以实现多个域名或IP地址的请求分发和处理。这样,Nginx可以根据不同的请求来提供不同的服务和内容。
37 0
|
4月前
|
中间件 Go 开发者
Go net http包
Go net http包
38 0
|
7天前
|
网络协议 安全 API
Android网络和数据交互: 什么是HTTP和HTTPS?在Android中如何进行网络请求?
HTTP和HTTPS是网络数据传输协议,HTTP基于TCP/IP,简单快速,HTTPS则是加密的HTTP,确保数据安全。在Android中,过去常用HttpURLConnection和HttpClient,但HttpClient自Android 6.0起被移除。现在推荐使用支持TLS、流式上传下载、超时配置等特性的HttpsURLConnection进行网络请求。
8 0
|
4月前
|
开发框架 .NET 数据库连接
解决HTTP错误500.19 - internal server error -内部服务器错误的终极指南
解决HTTP错误500.19 - internal server error -内部服务器错误的终极指南
693 0
|
1月前
|
Windows
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
102 0
|
1月前
|
存储 网络安全 数据安全/隐私保护
Windows Server 2019 IIS HTTPS证书部署流程详解
Windows Server 2019 IIS HTTPS证书部署流程详解
|
1月前
|
XML 开发框架 .NET
C# .NET面试系列八:ADO.NET、XML、HTTP、AJAX、WebService
## 第二部分:ADO.NET、XML、HTTP、AJAX、WebService #### 1. .NET 和 C# 有什么区别? .NET(通用语言运行时): ```c# 定义:.NET 是一个软件开发框架,提供了一个通用的运行时环境,用于在不同的编程语言中执行代码。 作用:它为多语言支持提供了一个统一的平台,允许不同的语言共享类库和其他资源。.NET 包括 Common Language Runtime (CLR)、基础类库(BCL)和其他工具。 ``` C#(C Sharp): ```c# 定义: C# 是一种由微软设计的面向对象的编程语言,专门为.NET 平台开发而创建。 作
174 2
|
2月前
|
C# Windows
.NET开源的一个小而快并且功能强大的 Windows 动态桌面软件
.NET开源的一个小而快并且功能强大的 Windows 动态桌面软件