• 简易httpserver 和客户端调用


    公用库

      1 using System;
      2 using System.Collections.Generic;
      3 using System.IO;
      4 using System.Linq;
      5 using System.Net;
      6 using System.Text;
      7 
      8 namespace AuCompLib
      9 {
     10     public sealed class HttpHelper
     11     {
     12       
     13         /// <summary>
     14         /// 发起Http请求
     15         /// </summary>
     16         /// <param name="requestDto">请求实体</param>
     17         /// <returns></returns>
     18         public static HttpReturnDto<object> DoHttp(HttpRequestDto requestDto)
     19         {
     20             var msg = new HttpReturnDto<object>();
     21             if (requestDto == null || string.IsNullOrEmpty(requestDto.Url) || string.IsNullOrEmpty(requestDto.Method))
     22             {
     23                 msg.IsSuccess = false;
     24                 msg.Message = "请求参数没有全部提供";
     25                 return msg;
     26             }
     27             HttpWebRequest httpRequest = GetHttpRequest(requestDto);
     28             try
     29             {
     30                 if (httpRequest != null)
     31                 {
     32                     var response = (HttpWebResponse)httpRequest.GetResponse();
     33                     var streamIn = response.GetResponseStream();
     34                     if (streamIn != null)
     35                     {
     36                         var reader = new StreamReader(streamIn);
     37                         if (httpRequest.Method=="GET")
     38                         {
     39                             msg.Data = Serializer.DeserializeObjectMs(streamIn);// reader.ReadToEnd();
     40                         }
     41                         else
     42                         {
     43                             msg.Data = reader.ReadToEnd();
     44                         }
     45                        
     46                         reader.Close();
     47                         streamIn.Close();
     48                         response.Close();
     49 
     50                         msg.IsSuccess = true;
     51                         msg.Message = "执行成功";
     52                     }
     53                 }
     54             }
     55             catch (Exception ex)
     56             {
     57                 msg.IsSuccess = false;
     58                 msg.Message = ex.Message;
     59                 return msg;
     60             }
     61             return msg;
     62         }
     63 
     64         /// <summary>
     65         /// 初始化http请求
     66         /// </summary>
     67         /// <param name="requestDto"></param>
     68         /// <returns></returns>
     69         private static HttpWebRequest GetHttpRequest(HttpRequestDto requestDto)
     70         {
     71             var config = requestDto.HttpConfigDto ?? new HttpConfig();
     72             HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(requestDto.Url);
     73             httpRequest.Method = requestDto.Method;
     74             httpRequest.Referer = config.Referer;
     75             //有些页面不设置用户代理信息则会抓取不到内容
     76             httpRequest.UserAgent = config.UserAgent;
     77             httpRequest.Timeout = config.Timeout;
     78             httpRequest.Accept = config.Accept;
     79             httpRequest.Headers.Set("Accept-Encoding", config.AcceptEncoding);
     80             httpRequest.ContentType = config.ContentType;
     81             httpRequest.KeepAlive = config.KeepAlive;
     82 
     83             switch (requestDto.Method.ToUpper())
     84             {
     85                 case "POST":
     86                     requestDto.Data = requestDto.Data ?? "";
     87                     var bData = Serializer.SerializeObjectMs(requestDto.Data); // Encoding.UTF8.GetBytes((char[])requestDto.Data);
     88                     httpRequest.ContentType = "application/xml;charset=utf-8";
     89                     httpRequest.ContentLength = bData.Length;
     90                     var streamOut = httpRequest.GetRequestStream();
     91                     streamOut.Write(bData, 0, bData.Length);
     92                     streamOut.Close();
     93                     break;
     94             }
     95             return httpRequest;
     96         }
     97     }
     98 
     99 
    100     public class HttpConfig
    101     {
    102         public string Referer { get; set; }
    103 
    104         /// <summary>
    105         /// 默认(text/html)
    106         /// </summary>
    107         public string ContentType { get; set; }
    108 
    109         public string Accept { get; set; }
    110 
    111         public string AcceptEncoding { get; set; }
    112 
    113         /// <summary>
    114         /// 超时时间(毫秒)默认100000
    115         /// </summary>
    116         public int Timeout { get; set; }
    117 
    118         public string UserAgent { get; set; }
    119 
    120         /// <summary>
    121         /// POST请求时,数据是否进行gzip压缩
    122         /// </summary>
    123         public bool GZipCompress { get; set; }
    124 
    125         public bool KeepAlive { get; set; }
    126 
    127         public string CharacterSet { get; set; }
    128 
    129         public HttpConfig()
    130         {
    131             this.Timeout = 2100000000;
    132             this.ContentType = "text/html; charset=" + Encoding.UTF8.WebName;
    133             this.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36";
    134             this.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
    135             this.AcceptEncoding = "gzip,deflate";
    136             this.GZipCompress = false;
    137             this.KeepAlive = true;
    138             this.CharacterSet = "UTF-8";
    139         }
    140     }
    141 
    142     /// <summary>
    143     /// 返回信息实体
    144     /// </summary>
    145     public class HttpRequestDto
    146     {
    147         /// <summary>
    148         /// 请求地址
    149         /// </summary>
    150         public string Url { get; set; }
    151         //请求数据
    152         public object Data { get; set; }
    153         /// <summary>
    154         /// 请求方法post/get
    155         /// </summary>
    156         public string Method { get; set; }
    157         /// <summary>
    158         /// 请求方法post/get
    159         /// </summary>
    160         public HttpConfig HttpConfigDto { get; set; }
    161     }
    162 
    163     /// <summary>
    164     /// 返回信息实体
    165     /// </summary>
    166     /// <typeparam name="T"></typeparam>
    167     public class HttpReturnDto<T>
    168     {
    169         public HttpReturnDto()
    170         {
    171             IsSuccess = false;
    172             Message = "操作失败";
    173         }
    174         //是否执行成功
    175         public bool IsSuccess { get; set; }
    176         //编码
    177         public string Code { get; set; }
    178         //信息
    179         public string Message { get; set; }
    180         //返回数据
    181         public T Data { get; set; }
    182     }
    183 }
    View Code

    序列化的 直接二进制序列化 没有使用Json

      1 using System.Runtime.Serialization;
      2 using System.Runtime.Serialization.Formatters.Binary;
      3 using System.IO;
      4 using System;
      5 using System.Runtime.Remoting.Messaging;
      6 
      7 public sealed class Serializer
      8 {
      9     private Serializer() { }
     10 
     11     public static string SerializeObject(object obj)
     12     {
     13         IFormatter formatter = new BinaryFormatter();
     14         string result = string.Empty;
     15         using (MemoryStream stream = new MemoryStream())
     16         {
     17             formatter.Serialize(stream, obj);
     18 
     19             byte[] byt = new byte[stream.Length];
     20             byt = stream.ToArray();
     21             //result = Encoding.UTF8.GetString(byt, 0, byt.Length);
     22 
     23             result = Convert.ToBase64String(byt);
     24             stream.Flush();
     25         }
     26         return result;
     27     }
     28 
     29     public static object DeserializeObject(string str)
     30     {
     31         IFormatter formatter = new BinaryFormatter();
     32         //byte[] byt = Encoding.UTF8.GetBytes(str);
     33 
     34         byte[] byt = Convert.FromBase64String(str);
     35         object obj = null;
     36         using (Stream stream = new MemoryStream(byt, 0, byt.Length))
     37         {
     38             obj = formatter.Deserialize(stream);
     39         }
     40         return obj;
     41     }
     42 
     43     public static byte[] SerializeObjectMs(object obj)
     44     {
     45         if (obj == null)
     46             return null;
     47         //内存实例
     48         using (MemoryStream ms = new MemoryStream())
     49         {
     50             //创建序列化的实例
     51             BinaryFormatter formatter = new BinaryFormatter();
     52             formatter.Serialize(ms, obj);//序列化对象,写入ms流中  
     53             byte[] bytes = ms.GetBuffer();
     54             return bytes;
     55         }    
     56     }
     57     public static object DeserializeObjectMs(byte[] bytes)
     58     {
     59         object obj = null;
     60         if (bytes == null)
     61             return obj;
     62         //利用传来的byte[]创建一个内存流
     63         MemoryStream ms = new MemoryStream(bytes);
     64         ms.Position = 0;
     65         BinaryFormatter formatter = new BinaryFormatter();
     66         obj = formatter.Deserialize(ms);//把内存流反序列成对象  
     67         ms.Close();
     68         return obj;
     69     }
     70     public static object DeserializeObjectMs(Stream msinput)
     71     {
     72         object obj = null;
     73 
     74         var resultStream = new MemoryStream();
     75         while (true)
     76         {
     77             int data = msinput.ReadByte();
     78             resultStream.WriteByte((byte)data);
     79             if (data == -1)
     80                 break;
     81         }
     82         resultStream.Position = 0;
     83         BinaryFormatter formatter = new BinaryFormatter();
     84         obj = formatter.Deserialize(resultStream);//把内存流反序列成对象  
     85         resultStream.Close();
     86         return obj;
     87     }
     88 
     89     private byte[] ReadLineAsBytes(Stream SourceStream)
     90     {
     91         var resultStream = new MemoryStream();
     92         while (true)
     93         {
     94             int data = SourceStream.ReadByte();
     95             resultStream.WriteByte((byte)data);
     96             if (data == 10)
     97                 break;
     98         }
     99         resultStream.Position = 0;
    100         byte[] dataBytes = new byte[resultStream.Length];
    101         resultStream.Read(dataBytes, 0, dataBytes.Length);
    102 
    103     
    104         return dataBytes;
    105     }
    106 
    107 }
    View Code

    server端  使用HttpListener

    View Code

    clint 端调用

     1 using AuCompLib;
     2 using System;
     3 using System.Collections.Generic;
     4 using System.Diagnostics;
     5 using System.Linq;
     6 using System.Runtime.InteropServices;
     7 using System.Runtime.Remoting.Messaging;
     8 using System.Text;
     9 using System.Threading;
    10 using System.Threading.Tasks;
    11 
    12 namespace ConsoleApp1
    13 {
    14     class Program
    15     {
    16         static void Main(string[] args)
    17         {
    18 
    19             double[,] my = new double[5, 2];
    20             for (int i = 0; i < 5; i++)
    21             {
    22                 for (int j = 0; j < 2; j++)
    23                 {
    24                     my[i, j] = ((i + 1) / 10f) + ((j + 1));
    25                 }
    26             }
    27 
    28             ProcessStartInfo startInfo = new ProcessStartInfo(@"AuComp.exe");
    29             startInfo.CreateNoWindow = true;
    30             startInfo.UseShellExecute = false;
    31             startInfo.RedirectStandardOutput = true;
    32             Process process = Process.Start(startInfo);
    33             process.WaitForExit();
    34             Thread.Sleep(1000);
    35             HttpHelper helper = new HttpHelper();
    36             var data = HttpHelper.DoHttp(new HttpRequestDto() { Method = "Post", Data = my, Url = "http://localhost:1080/api/" });
    37             var data2 = HttpHelper.DoHttp(new HttpRequestDto() { Method = "GET", Url = "http://localhost:1080/api/" + "?open=true&filter=0.3" });
    38             HttpHelper.DoHttp(new HttpRequestDto() { Method = "GET", Url = "http://localhost:1080/api/" });
    39 
    40         }
    41 
    42         [DllImport("ConvertArry.dll", EntryPoint = "Add")]
    43         public static extern int Add(int a, int b);
    44    }
    45 }
    View Code
  • 相关阅读:
    CentOS查看系统信息和资源使用已经升级系统的命令
    192M内存的VPS,安装Centos 6 minimal x86,无法安装node.js
    Linux限制资源使用的方法
    多域名绑定同一IP地址,Node.js来实现
    iOS 百度地图大头针使用
    iOS 从app跳转到Safari、从app打开电话呼叫
    设置cell背景色半透明
    AsyncSocket 使用
    iOS 监听键盘变化
    iOS 7 标签栏控制器进行模态视图跳转后变成透明
  • 原文地址:https://www.cnblogs.com/mrguoguo/p/13590484.html
Copyright © 2020-2023  润新知