C# 编写webserver

79 篇文章 63 订阅

        modular-2 Edge 的baseservice 可以接收windows 系统下的C# 编写的APP,编写时要使用一个简单的webserver。这只需要使用。NET 中的HttpListener;就可以完成了。

       将网页放置在debug 目录中,包括了 views,css,js,font和images 几个目录。这个测试软件中包括了POST 语句的json 格式,我们使用了newtonsoft.json 库,可以使用VS 中的NUget 安装到项目中。

program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace webserver
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpListener httpListener;
            httpListener = new HttpListener();
            httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            httpListener.Prefixes.Add("http://127.0.0.1:3100/");
            Console.WriteLine("C# web server example");
            httpListener.Start();
 
            new Thread(new ThreadStart(delegate {
                try
                {
                    loop(httpListener);
                }
                catch (Exception)
                {
                    httpListener.Stop();
                }
            })).Start();
        }

        public static string GetRequestPostData(HttpListenerRequest request)
        {
            if (!request.HasEntityBody)
            {
                return null;
            }
            using (System.IO.Stream body = request.InputStream) // here we have data
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        public class vResult
        {
            [JsonProperty("status")]
            public string Status { get; set; }

            [JsonProperty("value")]
            public int Value { get; set; }
        }

        public class jsonRPCReponse
        {
            [JsonProperty("result")]
            public vResult Result { get; set; }

            [JsonProperty("id")]
            public int ID { get; set; }
        }

        private static void loop(HttpListener httpListener)
        {
            while (true)
            {
                HttpListenerContext context = httpListener.GetContext();
                HttpListenerRequest hRequest = context.Request;
                HttpListenerResponse hResponse = context.Response;
           

                if (hRequest.HttpMethod == "POST")
                {
                    string path = hRequest.RawUrl;
                    string[] detail = path.Split('/');
                    Console.WriteLine("POST"+detail[2]);
                    string message = GetRequestPostData(hRequest);
                    Console.WriteLine(message);
                    JObject requestjson = (JObject)JsonConvert.DeserializeObject(message);

                    string methodName = requestjson["method"].ToString();
                    jsonRPCReponse rpcresponse = new jsonRPCReponse();
                    vResult rpcresult = new vResult();
                    rpcresult.Status = methodName;
                    rpcresult.Value = 0;
                    rpcresponse.Result = rpcresult;
                    rpcresponse.ID= Convert.ToInt16(requestjson["id"]);

                    string resMessage = JsonConvert.SerializeObject(rpcresponse);
                    Console.WriteLine(resMessage);
                    byte[] res = Encoding.UTF8.GetBytes(resMessage);
                    hResponse.OutputStream.Write(res, 0, res.Length);
                    hResponse.OutputStream.Close();
                }
                else if (hRequest.HttpMethod == "GET")
                {                 
                    Console.WriteLine("GET:" + hRequest.RawUrl);
                    string path = hRequest.RawUrl;
                    string[] detail = path.Split('/');
                    string filetype = detail[1];
                    if ((filetype.CompareTo("views")==0)||
                      (filetype.CompareTo("css")==0) ||
                      (filetype.CompareTo("font") == 0) ||
                      (filetype.CompareTo("js") == 0) ||
                      (filetype.CompareTo("images")==0)  
                      )

                    {
                        Console.WriteLine("valid");
                        if (filetype.CompareTo("views") == 0)
                               filetype = "html";
                        if (filetype.CompareTo("images") == 0)
                        {
                            Console.WriteLine("image/" + Path.GetExtension(detail[2]));
                            hResponse.ContentType = "image/"+ Path.GetExtension(detail[2]);

                        }
                        else

                          hResponse.ContentType = "text/" + filetype + ";charset=utf-8";

                        string filename = detail[2];
                        int index;
                        if (filetype.CompareTo("font") == 0)
                        {
                            index = detail[2].IndexOf('?');
                            filename = detail[2].Substring(0,index);
                            Console.WriteLine(filename);
                        }
                        Console.WriteLine("text/" + filetype + ";charset=utf-8");
                        Console.WriteLine("file Name"+ "./" + detail[1] + "/" +filename);
                        if (File.Exists("./" + detail[1] + "/" + filename))
                        {
                FileStream fileStream = File.OpenRead("./" + detail[1] + "/" + filename);

                            int bufferSize = 1024;
                            byte[] buffer = new byte[bufferSize];
                            int bytesRead = 0;
                        while ((bytesRead = fileStream.Read(buffer, 0, bufferSize)) != 0)
                            {
                                hResponse.OutputStream.Write(buffer, 0, bytesRead);
                            } // end while
                        } else
                        {
                            Console.WriteLine("file not found");
                        }
                    }
                    hResponse.OutputStream.Close();
                }
            }

          //  httpListener.Close();
        }
    }
}


index.html


<!DOCTYPE html>

<html lang="zh-CN">

  <head>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>modular-2 system setup</title>

  <link href="/css/bootstrap.min.css" rel="stylesheet" type="text/css">

  <link href="/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css">

  <link href="/css/default.css" rel="stylesheet" type="text/css">

  <link href="/css/font-awesome.min.css" rel="stylesheet" type="text/css">

  <script src="/js/jquery-3.4.1.min.js"></script>

   <script src="/js/bootstrap.min.js"></script>

   <script src="/js/bootstrap-switch.min.js"></script> 

   

   <style>

       .led {

        margin: 5px; 

     background-color: blue;

     width:15px;

     height:15px;

     display:inline-block;

   } 

   </style>

   <script>

   function post_it()

   {

   var jsonrpc={

    "method":"digitalOur.write",

    "pin":1,

    "value":1

  }

  console.log(jsonrpc);

$.ajax({ 

      type : "POST", 

      url : "/api/request", 

      data : JSON.stringify(jsonrpc), 

      contentType : "application/json", 

      dataType : "json", 

      complete:function(data) { 

        console.log(data.responseJSON);  

  

      } 

    }); 

   }

   </script>

  </head>

 

 <body class="container">

   <!-- Image and text -->

   <nav class="navbar fixed-top  navbar-default ">

      <a class="nav-link" href="http://192.168.31.98:2019/home/views/index.html"><i class="icon-home icon-2x "> </i>主页</a>

      <a class="navbar-brand" href="#">C# based App</a>

      <a class="nav-link  pull-right" href="http://localhost:9100/views/gpio_setup.html"><i class="icon-cogs icon-2x"> </i>设置</a>

    </nav>

    <button  class="btn btn-primary btn-lg " οnclick="post_it()" >POST Test</button>

   

</div>

 

  </body>

  </html>

该程序在VS2017 上调试成功。

 

https://blog.csdn.net/yaojiawan/article/details/101535377 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值