首页 文章 精选 留言 我的

精选列表

搜索[core],共10000篇文章
优秀的个人博客,低调大师

ASP.NET Core on K8S深入学习(3-2)DaemonSet与Job

​ 一、DaemonSet 1.1 DaemonSet是个啥? Deployment的部署可以指定副本Pod分布在多个Node节点上,且每个Node都可以运行多个Pod副本。而DaemonSet呢,它倔强地保证在每个Node上都只运行一个Pod副本。 回想一下项目经历,有哪些场景满足这个特质呢?是不是一些集群的日志、监控或者其他系统管理应用? 日志收集,比如fluentd,logstash等 系统监控,比如Prometheus Node Exporter,collectd,New Relic agent,Ganglia gmond等 系统程序,比如kube-proxy,kube-dns,glusterd,ceph等 Prometheus Node Exporter Dashboard 1.2 K8S中的DaemonSet 在K8S中,就有一些默认的使用DaemonSet方式运行的系统组件,比如我们可以通过下面一句命令查看: kubectl get daemonset --namespace=kube-system 可以看到,kube-flannel-ds 和 kube-proxy 是K8S以DaemonSet方式运行的系统组件,分别为K8S集群负责提供网络连接支持和代理支持,这里不深入讨论它们的详细情况,只需要了解它们负责什么就可以了。在通过查看Pod副本,看看各个节点的分布情况: kubectl get pod --namespace=kube-system -o wide 可以看到,它们两分布在各个Node节点上(这里是我的K8S集群中的所有节点了),且每个节点上只有一个Pod副本。 1.3DaemonSet的创建和运行 同之前的创建资源方式一样,仍然采用通过YAML配置文件的方式进行创建,只需要指定kind: DaemonSet即可: apiVersion: apps/v1 kind: DaemonSet 这里我们以Prometheus Node Exporter为例演示一下如何运行我们自己的DaemonSet。 _PS:_Prometheus是流行的系统监控方案,而Node Exporter负责收集节点上的metrics监控数据,并将数据推送给Prometheus。Prometheus则负责存储这些数据,Grafana最终将这些数据通过网页以图形的形式展现给用户。 下面是yaml配置文件对于DaemonSet资源清单的定义: apiVersion: apps/v1 kind: DaemonSet metadata: name: node-exporter-daemonset namespace: agent spec: selector: matchLabels: app: prometheus template: metadata: labels: app: prometheus spec: hostNetwork: true containers: - name: node-exporter image: prom/node-exporter imagePullPolicy: IfNotPresent command: - /bin/node_exporter - --path.procfs - /host/proc - --path.sysfs - /host/sys - --collector.filesystem.ignored-mount-points - ^/(sys|proc|dev|host|etc)($|/) volumeMounts: - name: proc mountPath: /host/proc - name: sys mountPath: /host/sys - name: root mountPath: /rootfs volumes: - name: proc hostPath: path: /proc - name: sys hostPath: path: /sys - name: root hostPath: path: / 这里暂且不纠结其中的配置内容,包括Host网络、容器启动命令以及Volume,后面会专题介绍。 同样,通过kubectl创建资源: kubectl apply -f node-exporter.yaml 然后,通过kubectl查看Pod分布情况: 可以看出,我们的Prometheus Node Exporter部署成功,且分别在两个Node节点都只部署了一个Pod副本。 二、Job 2.1 关于Job 对于ReplicaSet、Deployment、DaemonSet等类型的控制器而言,它希望Pod保持预期数目并且持久运行下去,除非用户明确删除,否则这些对象一直存在,因此可以说他们说持久服务型任务的。 对于非耐久性任务,比如压缩文件,任务完成后,Pod需要结束运行,不需要Ppod继续保持在系统中,这个时候就要用到Job。因此也可以说,Job是对ReplicaSet、Deployment、DaemonSet等持久性控制器的补充。 2.2 Job的创建与运行 同之前的创建资源方式一样,仍然采用通过YAML配置文件的方式进行创建,需要指定apiVersioin: batch 以及 kind: Job即可: apiVersion: batch/v1 (1)第一个Job 这里我们以一个简单的小Job为例,看看一个简单的Job:当Job启动后,只运行一个Pod,Pod运行结束后整个Job也就立刻结束。 apiVersion: batch/v1 kind: Job metadata: name: edc-job-hello-job namespace: jobs spec: template: metadata: labels: app: edc-job-hello-job spec: containers: - name: hello-job image: busybox imagePullPolicy: IfNotPresent command: ["echo", "hello edison's k8s job!"] restartPolicy: Never 这里需要注意的是,对Job而言,其restartPolicy只能为Never或者OnFailure,这也是它与其他控制器的差别(如Deployment控制器还允许设置为Always)。这个Job要执行的任务也很简单,就是输出一段话“hello edison's k8s job!”就结束其生命了。 _PS:_这里用到了一个busybox的镜像,busybox是一个软件工具箱,里边集成了Linux中几百个常用的Linux命令以及工具。如果我们只需要一个小型的Linux运行环境跑命令,完全可以使用这个busybox镜像,而不用拉取一个CentOS镜像。 通过查看Job运行情况可以知道,其运行结束就结束了,如下图所示,变成了Completed状态。 kubectl get pod -n jobs 还可以通过查看Log看看这个Job留下的足迹: kubectl get pod -n jobs --show-all kubectl logs edc-job-hello-job-whcts (2)并行Job 如果希望能够同时并行运行多个Pod以提高Job的执行效率,Job提供了一个贴心的配置:parallesim。例如下面的配置,我们将上面的小Job改为并行运行的Pod数量设置为3。 apiVersion: batch/v1 kind: Job metadata: name: edc-job-hello-job namespace: jobs spec: parallelism: 3 template: metadata: labels: app: edc-job-hello-job spec: containers: - name: hello-job image: busybox imagePullPolicy: IfNotPresent command: ["echo", "hello edison's k8s job!"] restartPolicy: OnFailure _PS:_默认parallelism值为1 使用上面的配置文件创建了资源后,通过以下命令查看验证: kubectl get job -n jobs kubectl get pod -o wide -n jobs 可以看出,Job一共启动了3个Pod,都是同时结束的(可以看到三个Pod的AGE都是相同的)。 此外,Job还提供了一个completions属性使我们可以设置Job完成的Pod总数,还是上面的例子: apiVersion: batch/v1 kind: Job metadata: name: edc-job-hello-job namespace: jobs spec: parallelism: 3 completions: 6 template: metadata: labels: app: edc-job-hello-job spec: containers: - name: hello-job image: busybox imagePullPolicy: IfNotPresent command: ["echo", "hello edison's k8s job!"] restartPolicy: OnFailure _PS:_默认completions也为1 上面的配置意思就是:每次运行3个Pod,直到总共有6个Pod就算成功完成。同样通过命令验证一下: 可以看到,状态和AGE都符合预期,第一批3个Pod的AGE为12s,第二批3个Pod的AGE为14s。 2.3 CronJob的创建与运行 我们都知道在Linux中,Cron程序可以定时执行任务,而在K8S中也提供了一个CronJob帮助我们实现定时任务。 继续以上面的例子,我们增加一些配置: apiVersion: batch/v1beta1 kind: CronJob metadata: name: edc-cron-job namespace: jobs spec: schedule: "*/1 * * * *" jobTemplate: spec: template: spec: containers: - name: cron-job image: busybox imagePullPolicy: IfNotPresent command: ["echo", "hello edison's k8s cron job!"] restartPolicy: OnFailure 上面加粗的配置是CronJob的独有配置,需要注意的是schedule,它的格式和Linux Cron一样,这里的"*/1 * * * *"代表每一分钟启动执行一次。对于CronJob,它需要的是jobTemplate来定义Job的模板。 同样,隔几分钟之后,通过命令来验证一下: 可以看到,在过去的三分钟里,每一分钟都启动了一个Pod,符合预期。 三、小结 Deployment可以满足我们大部分时候的应用部署(无状态服务类容器),但是针对一些特殊的场景应用,Deployment就无法胜任了。比如日志收集、系统监控等场景,就可以使用今天介绍的DaemonSet。又比如批处理定时任务,则可以使用今天介绍的Job/CronJob。 参考资料 (1)CloudMan,《每天5分钟玩转Kubernetes》 (2)李振良,《一天入门Kubernets教程》 (3)马哥(马永亮),《Kubernetes快速入门》 (4)阿龙,《Kubernetes系列-07.Pod控制器详解》 (5)elvis,《K8S-Job与CronJob的使用》 (6)五星上炕,《Kubernetes之Job详解》

优秀的个人博客,低调大师

阿里云物联网 .NET Core 客户端 | CZGL.AliIoTClient:4. 设备上报属性

设备自身 CPU 温度、电源输入电压、内存使用率等,以及接入到设备的传感器如温度传感器、光敏传感器等,这些硬件的数据输出即是 属性 。 设备将这些硬件的数据上传到阿里云物联网平台,实时显示这些设备的状态和实测数据,这个过程是 上传设备属性 。 1)定义物模型 在阿里云物联网控制台,点击 产品 -> 功能定义 -> 添加自定义功能 填入一下内容: 功能类型:属性 功能名称: CPU温度 标识符: cpu_temperature 数据类型: float (单精度浮点型) 取值范围:0-120 步长: 0.1 单位: 摄氏度 / °C 读写类型:只读 再定义一个属性: 功能类型:属性 功能名称: 格力空调温度 标识符: gree_temperature 数据类型: float (单精度浮点型) 取值范围:0-35 步长: 0.1 单位: 摄氏度 / °C 读写类型:读写 注意的是,表示符是区分大小写的,相当于 C# 中的变量,笔者这里建议统一使用小写,具体原因后面说明。 注意:读写类型,一个只读、一个读写。 2)编写模型 前面说过, Alink json 是阿里云定义具有一定格式的 Json , 因此这些属性数据是以 Json 形式上传。在 C# 中,可以通过 类 快速生成 Json 。 | 参数 | 类型 | 说明 | |---|---|---| |id |string |消息ID号,在这个设备的生涯中,ID应当是唯一的。可以使用时间戳或guid||version| string| 协议版本号,目前协议版本号为1.0。固定 "1.0" 即可||params| Object| 属性数据,里面包含多个属性对象,每个属性对象包含上报时间(time)和上报的值(value)。||time |long| 属性上报时间。||value |object| 上报的属性值。||method |string| 固定取值 thing.event.property.post| 那么,我们要编写一个类,存储信息,然后转为 Alink json 上传到阿里云物联网服务器。在编写这个模型前,预览要生成的 Alink json : { "id": "123456789", "version": "1.0", "params": { "cpu_temperature": { "value": 58.6, "time": 1524448722000 }, "gree_temperature": { "value": 26.6, "time": 1524448722000 } }, "method": "thing.event.property.post" } 我们只需关注 params 部分的编写即可。 在控制台程序中,新建一个类 TestModel。 public class TestModel { public string id { get { return DateTime.Now.Ticks.ToString(); } set { } } public string version { get { return "1.0"; } set { } } public Params @params { get; set; } public class Params { /* * */ } public string @method { get { return "thing.event.property.post"; } set { } } } 这样定义后,我们使用时,只需定义 params 部分即可, id、version等,不需要自己动态取值,做重复劳动。 上面有个 @params ,这是因为 params 是 C# 的关键字,命名字段时为了取消冲突所以加个 @ 。 根据我们在阿里云物联网控制台定义的 属性 ,继续补充内容: public class TestModel { public string id { get { return DateTime.Now.Ticks.ToString(); } set { } } public string version { get { return "1.0"; } set { } } public Params @params { get; set; } public class Params { public Cpu_temperature cpu_temperature { get; set; } public Gree_temperature gree_temperature { get; set; } public class Cpu_temperature { public float value{ get; set; } public long time { get; set; } } public class Gree_temperature { public float value { get; set; } public long time { get; set; } } } public string @method { get { return "thing.event.property.post"; } set { } } } 问题是,这样写还不行,因为还没有给 TestModel 里的类进行实例化。 我们可以利用 构造函数 对里面的引用类型进行实例化,当然亦可编写依赖注入容器。。 public class TestModel { public string id { get { return DateTime.Now.Ticks.ToString(); } set { } } public string version { get { return "1.0"; } set { } } public Params @params { get; set; } public TestModel() { @params = new Params(); } public class Params { public Cpu_temperature cpu_temperature { get; set; } public Gree_temperature gree_temperature { get; set; } public Params() { cpu_temperature = new Cpu_temperature(); gree_temperature = new Gree_temperature(); } public class Cpu_temperature { public float value{ get; set; } public long time { get; set; } } public class Gree_temperature { public float value { get; set; } public long time { get; set; } } } public string method { get { return "thing.event.property.post"; } set { } } } 3)上传设备属性数据 编写控制台程序,引入 CZGL.AliIoTClient ,编写基础代码(请替换 DeviceOptions 的信息): static AliIoTClientJson client; static void Main(string[] args) { // 创建客户端 client = new AliIoTClientJson(new DeviceOptions { ProductKey = "a1A6VVt72pD", DeviceName = "json", DeviceSecret = "7QrjTptQYCdepjbQvSoqkuygic2051zM", RegionId = "cn-shanghai" }); // 设置要订阅的Topic、运行接收内容的Topic string[] topics = new string[] { client.CombineHeadTopic("get") }; // 使用默认事件 client.UseDefaultEventHandler(); // 连接服务器 client.ConnectIoT(topics,null,60); ToServer(); // 自定义方法,后面说明 Console.ReadKey(); } 再 Program 类中,编写一个方法用来收集属性数据、上传属性数据: public static void ToServer() { // 实例化模型 TestModel model = new TestModel(); // 设置属性值 model.@params.cpu_temperature.value = 56.5F; model.@params.cpu_temperature.time =AliIoTClientJson.GetUnixTime(); // 低碳环境、节约资源,从你我做起,夏天空调不低于 26° model.@params.gree_temperature.value=26.0F; model.@params.gree_temperature.time=AliIoTClientJson.GetUnixTime(); // 上传属性数据 client.Thing_Property_Post<TestModel>(model,false); } 启动控制台应用,在阿里云物联网控制台,打开设备,点击 运行状态 ,即可看到上传的属性数据。文章后面会详细说明 CZGL.AliIoTClient 关于属性上传的具体情况。 当然,这样的数据只是固定赋值的,这里只是演示,具体数据需要开发者采集。下面给出一些模拟数据的方法。 4)模拟数据 笔者编写了三个数据模拟方法: 不需要理会里面是怎么写的,仅是个模拟数据的工具而已,你也可以自己编写相应的模拟数据方法。 里面有四个参数,对应:原始值、最小值、最大值、波动范围。 /// <summary> /// 模拟数据 /// </summary> public static class DeviceSimulate { /// <summary> /// /// </summary> /// <param name="original">原始数据</param> /// <param name="range">波动范围</param> /// <param name="min">最小值</param> /// <param name="max">最大值</param> /// <returns></returns> public static int Property(ref int original, int min, int max, int range) { int num = (new Random()).Next(0, range + 1); bool addorrm; if (original + num > max || original > max) addorrm = false; else if (original < min || original - num < min) addorrm = true; else addorrm = ((new Random()).Next(1, 3) > 1) ? true : false; if (addorrm == true) original += num; else original -= num; return original; } public static float Property(ref float original, float min, float max, int range = 8) { original = float.Parse(original.ToString("#0.00")); float num = float.Parse(((new Random()).NextDouble() / range).ToString("#0.00")); bool addorrm; if (original + num > max || original > max) addorrm = false; else if (original < min || original - num < min) addorrm = true; else addorrm = ((new Random()).Next(1, 3) > 1) ? true : false; if (addorrm == true) original += num; else original -= num; original = float.Parse(original.ToString("#0.00")); return original; } public static double Property(ref double original, double min, double max, int range = 8) { original = double.Parse(original.ToString("#0.0000")); double num = double.Parse(((new Random()).NextDouble() / range).ToString("#0.0000")); bool addorrm; if (original + num > max || original > max) addorrm = false; else if (original < min || original - num < min) addorrm = true; else addorrm = ((new Random()).Next(1, 3) > 1) ? true : false; if (addorrm == true) original += num; else original -= num; original = double.Parse(original.ToString("#0.0000")); return original; } } int 模拟数据 range 是指每次生成 [0,range] 范围的增/减量, 例如 初始值 56 , range = 2 ,那么可能 56±0 或 56±1 或 56±2 ,是增还是减,是随机的。但是设置 min 、 max 后,最后生成的值会在此范围内波动。 float、double 模拟数据 对应 float、double,range 的值越大,波动范围越小。默认 range = 8,大概就是每次 0.1 的波动范围。 其中,float 小数保留两位, double 小数保留 4 位, 需要更高或减少小数位数,修改一下 ...ToString("#0.0000") 模拟属性数据 接下来我们模拟一下两个属性的数据。 在 Program 中定义两个变量存储 cpu 和 空调 数据。 static float cpu_temperature = 50.0F; static float gree_temperature = 26.0F; 修改 ToServer() 方法 public static void ToServer() { // 实例化模型 TestModel model = new TestModel(); // 设置属性值 model.@params.cpu_temperature.value = DeviceSimulate.Property(ref cpu_temperature, 40, 60, 8); model.@params.cpu_temperature.time = AliIoTClientJson.GetUnixTime(); // 低碳环境、节约资源,从你我做起,夏天空调不低于 26° model.@params.gree_temperature.value = DeviceSimulate.Property(ref gree_temperature, 40, 60, 8); ; model.@params.gree_temperature.time = AliIoTClientJson.GetUnixTime(); // 上传属性数据 client.Thing_Property_Post<TestModel>(model, false); } 在 Main() 方法里增加代码: // 定时上传数据 while (true) { ToServer(); Thread.Sleep(1000); } 至此,已经基本完成。 完整代码如下: class Program { static AliIoTClientJson client; static void Main(string[] args) { // 创建客户端 client = new AliIoTClientJson(new DeviceOptions { ProductKey = "a1A6VVt72pD", DeviceName = "json", DeviceSecret = "7QrjTptQYCdepjbQvSoqkuygic2051zM", RegionId = "cn-shanghai" }); // 设置要订阅的Topic、运行接收内容的Topic string[] topics = new string[] { client.CombineHeadTopic("get") }; // 使用默认事件 client.UseDefaultEventHandler(); // 连接服务器 client.ConnectIoT(topics, null, 60); // 定时上传数据 while (true) { ToServer(); Thread.Sleep(1000); } Console.ReadKey(); } static float cpu_temperature = 50.0F; static float gree_temperature = 26.0F; public static void ToServer() { // 实例化模型 TestModel model = new TestModel(); // 设置属性值 model.@params.cpu_temperature.value = DeviceSimulate.Property(ref cpu_temperature, 40, 60, 8); model.@params.cpu_temperature.time = AliIoTClientJson.GetUnixTime(); // 低碳环境、节约资源,从你我做起,夏天空调不低于 26° model.@params.gree_temperature.value = DeviceSimulate.Property(ref gree_temperature, 40, 60, 8); ; model.@params.gree_temperature.time = AliIoTClientJson.GetUnixTime(); // 上传属性数据 client.Thing_Property_Post<TestModel>(model, false); } /// <summary> /// 模拟数据 /// </summary> public static class DeviceSimulate { /// <summary> /// /// </summary> /// <param name="original">原始数据</param> /// <param name="range">波动范围</param> /// <param name="min">最小值</param> /// <param name="max">最大值</param> /// <returns></returns> public static int Property(ref int original, int min, int max, int range) { int num = (new Random()).Next(0, range + 1); bool addorrm; if (original + num > max || original > max) addorrm = false; else if (original < min || original - num < min) addorrm = true; else addorrm = ((new Random()).Next(1, 3) > 1) ? true : false; if (addorrm == true) original += num; else original -= num; return original; } public static float Property(ref float original, float min, float max, int range = 8) { original = float.Parse(original.ToString("#0.00")); float num = float.Parse(((new Random()).NextDouble() / range).ToString("#0.00")); bool addorrm; if (original + num > max || original > max) addorrm = false; else if (original < min || original - num < min) addorrm = true; else addorrm = ((new Random()).Next(1, 3) > 1) ? true : false; if (addorrm == true) original += num; else original -= num; original = float.Parse(original.ToString("#0.00")); return original; } public static double Property(ref double original, double min, double max, int range = 8) { original = double.Parse(original.ToString("#0.0000")); double num = double.Parse(((new Random()).NextDouble() / range).ToString("#0.0000")); bool addorrm; if (original + num > max || original > max) addorrm = false; else if (original < min || original - num < min) addorrm = true; else addorrm = ((new Random()).Next(1, 3) > 1) ? true : false; if (addorrm == true) original += num; else original -= num; original = double.Parse(original.ToString("#0.0000")); return original; } } } 运行控制台程序,然后打开阿里云物联网控制台,查看设备的运行状态,打开 自动刷新 ,查看数据变化。 如果你觉得每次波动得范围太大,可以把 range 改大一些,如果你觉得数据不稳定, 可以把 min - max 的范围改小一些,模拟的数据值将在此范围波动。 5)设备属性 - CZGL.AliIoTClient 首先要说明,产品创建前,需要设置为 Alinkjson/透传 产品, 因此 CZGL.AliIoTClient 设置了两个客户端类。 类名 说明 AliIoTClientJson 以Alink json形式上传数据 AliIoTClientBinary 以透传形式上传数据 这两个类,仅在 属性、事件、服务 三个功能中数据上传形式有差别,连接服务器、普通Topic等其它数据的使用是完全一致的。 一个产品只能定义一种上传数据的形式。 CZGL.AliIoTClient 中上传属性的方法(Alink json): // 不需要SDK处理任何中间过程,直接把数据上传。 // 那你需要先将数据存储到json中,在转成byte[],由SDK发送。 public int Thing_Property_Post(byte[] json) // 由SDK帮你发送原始的json,是否需要将json转为小写再发送,默认 true public int Thing_Property_Post(string json, [bool isToLwer = True]) // 设置要发送的json;是否转为小写;设置编码格式,为空则为UTF8 public int Thing_Property_Post(string json, [bool isToLwer = True], [System.Text.Encoding encoding = null]) // 直接传入模型,什么都不需要管,SDK转换后上传 public int Thing_Property_Post<TModel>(TModel model, [bool isToLower = True]) 获取 UNIX 时间: 由于阿里云要求上传的属性数据等,要带上 Unix 时间,所以笔者一并写在 CZGL.AliIoTClient 了。 public static long GetUnixTime() 使用示例参考上面的过程。 透传 如果你想使用透传,则使用 AliIoTClientBinary 类, // 设备上传属性--透传 public int Thing_Property_UpRaw(byte[] bytes) // 设备上传属性--透传,转为 Base 64位加密后上传 public int Thing_Property_UpRawToBase64(byte[] bytes, [System.Text.Encoding encoding = null]) 6)关于透传 透传以二进制报文形式上传,例如 0x020000007b00 ,这里是 16 进制,每两位一个字节。 如果是 2进制 ,则是 8位 一个字节。 透传需要在阿里云物联网控制台创建 透传 产品后,设置脚本,将透传数据 转为 Alink json。 透传数据是自定义的,以字节为单位,其中有5个字节为特定字节,以字节位进行拆分的。 记住,是以字节为单位。 透传数据格式标准: 字段 字节数 帧类型 1字节 请求ID 4字节 属性数据 N个字节 帧类型: 值(16进制) 说明 0x00 属性上报 0x01 属性设置 0x02 上报数据返回结果 0x03 属性设置设备返回结果 0xff 未知的命令 举例说明 很多人是直接把 10进制 或 16进制 直接转换成 2进制 。 例如 0x020000007b00,转为 2进制 :100000000000000000000000000111101100000000。但是这样是错误的。 以上面 cpu 和 空调温度 举例,要上传属性数据,帧类型为 0x00。 | 属性 | 10进制 | 16进制 | 2进制 | 划一下2进制 | | --------------- | ------ | -------- | ----------- | ----------- | | cpu_temperature | 56 | 38 | 00111000 | 00 11 10 00 | | gree_temperature | 26 | 1a | 00011010 | 00 01 10 10 | 应当这样拆分和设置值: 字节类转 字节数 16进制 2进制 进制表示 无 0x 无 帧类型 1字节 00 00000000 ID 4字节 00 00 00 7b 00000000 00000000 00000000 01111011 cpu_temperature 1 字节 38 00111000 gree_temperature 1 字节 1a 00011010 16进制数据: 0x000000007b381a 2进制数据: 00000000000000000000000000000000011110110011100000011010 将 16进制 或 2进制 的数据存储到 byte[] 变量中,切记要强制转换。 存储时,一个 byte 为一个字节,M个字节,则 byte[M]。 存储: 使用 16进制 存储透传数据,2进制弄不来的。 :joy: :joy: :joy: 有些同学非要用 2进制 存储,反正我是弄不来,用 二进制 数值 存储,这个触发我的知识盲区了。 示例(仅对 AliIoTClientBinary 客户端有效): // 存储透传数据 byte[] b = new byte[7]; b[0] = 0x00; b[1] = 0x00; b[2] = 0x00; b[3] = 0x00; b[4] = 0x7b; b[5] = 0x38; b[6] = 0x1a; // 上传透传数据 client.Thing_Property_UpRaw(b); 如果上报属性,要求 请输入二进制数据Base64编码后的字符串,可以使用 byte[] b = new byte[7]; b[0] = 0x00; b[1] = 0x00; b[2] = 0x00; b[3] = 0x00; b[4] = 0x7b; b[5] = 0x38; b[6] = 0x1a; // client.Thing_Property_UpRaw(b); client.Thing_Property_UpRawToBase64(b); 透传数据的坑很多,这里 CZGL.AliIoTClient 只提供如何处理数据和上传数据,云端的脚本解析请参考 https://help.aliyun.com/document_detail/114621.html?spm=a2c4g.11186623.2.13.209b65b9Q9z0Nx#concept-185365 7)后续说明 其实,每次上传服务器都会作出响应,CZGL.AliIoTClient 默认不接收这些响应信息。 你可以使用 OpenPropertyPostReply() 接收设备属性上传后服务器的响应,应当在连接服务器前使用此方法 使用 Close.PropertyPostReply() 取消接收设备属性上传后服务器的响应。 示例: // 。。。 client.ClosePropertyPostReply(); // 连接服务器 client.ConnectIoT(topics, null, 60); 上传属性数据,可以分开上传,不需要每次都要上传全部的属性。需要更新哪个属性,就上传这个属性。

优秀的个人博客,低调大师

阿里云物联网 .NET Core 客户端 | CZGL.AliIoTClient:5. 设置设备属性

在上一章,格力空调温度 gree_temperature 设置了 读写 权限,因为空调的输出温度是可以被设置的。 CPU 温度是根据实际情况进行采集,而 空调温度 是遥控器设置的,服务器可以或者这个温度数据,同时也可以设置这个数据。 读写权限表示服务器有权限下发指令设置设备的属性。 注意的是,只有 读/读写 两种情况,没有 写 。 1)允许服务器设置设备属性 通讯就是 订阅/推送 、数据上下传输,本身没有这么复杂,无论 是属性、事件、服务,本质还是 Topic。 CZGL.AliIoTClient 作了细致的划分(快夸笔者),里面设置了很多参数,这样更自由、方便。 第3章已经说到如何打开和取消响应和其它功能,这里就不再解释。 以下为初始代码,将会在此基础上进行说明(请修改 DeviceOptions 的信息): static AliIoTClientJson client; static void Main(string[] args) { // 创建客户端 client = new AliIoTClientJson(new DeviceOptions { ProductKey = "a1A6VVt72pD", DeviceName = "json", DeviceSecret = "7QrjTptQYCdepjbQvSoqkuygic2051zM", RegionId = "cn-shanghai" }); client.OpenPropertyDownPost(); // 设置要订阅的Topic、运行接收内容的Topic string[] topics = new string[] { client.CombineHeadTopic("get") }; // 使用默认事件 client.UseDefaultEventHandler(); // 连接服务器 client.ConnectIoT(topics, null, 60); Console.ReadKey(); } 在 Console.ReadKey() 前加一行代码,运行服务器下发属性设置命令: client.OpenPropertyDownPost(); 运行程序。 2)下发命令 打开阿里云物联网控制台,进入 在线调试 ,然后选择前面已经创建的产品、设备。 你也可以直接打开: https://iot.console.aliyun.com/lk/monitor/debug进行如下设置: 调试设备:调试真实设备 功能: 格力空调温度(gree_temperature) 方法: 设置 然后将输入框里的数值改为 20.0 ,点击 发送指令 { "gree_temperature": 20 } 然后你可以看到控制台程序收到了指令: get topic message,Date: 16:52:55 topic: /sys/a1A6VVt72pD/json/thing/service/property/set get messgae : {"method":"thing.service.property.set","id":"666237842","params":{"gree_temperature":20},"version":"1.0.0"} 由于使用 Alink json,所以服务器下发的指令实际上是这样的: {"method":"thing.service.property.set","id":"666237842","params":{"gree_temperature":20},"version":"1.0.0"} 那为什么会输出其它东西呢?这是因为 CZGL.AliIoTClient 种设置了多个默认的事件方法, 它会输出收到的消息内容(message)等信息,你可以自定义方法来处理。 将 字符串格式化后: { "method": "thing.service.property.set", "id": "666237842", "params": { "gree_temperature": 20 }, "version": "1.0.0" } 但是目前只能收到服务器下发的命令,还没有写如何处理这些命令的方法,这需要你编写相应的方法绑定到委托事件中。 当收到属性消息时,会触发这些方法。如何设置,请参考后面的章节。 3)做出响应 当你收到服务器下发的指令时,你可以对这条 Topic 做出响应。 // 返回消息ID public int Thing_Property_set(CZGL.AliIoTClient.PropertyDownModel model, [bool isToLower = True]) public int Thing_Property_set(CZGL.AliIoTClient.PropertyDownModel model, [bool isToLower = True], [System.Text.Encoding encoding = null]) public int Thing_Property_set<TModel>(TModel model, [bool isToLower = True]) 实际上,不需要做出响应。。。如果有需要的话,可以自定义方法,在方法里面加上响应,绑定到委托里,自动响应。 如何设置,请参考后面的章节。

优秀的个人博客,低调大师

阿里云物联网 .NET Core 客户端 | CZGL.AliIoTClient:4.1 上报位置信息

阿里云物联网的位置服务,并不是完全独立的功能。位置信息包含 二维、三维,位置数据来源于属性的上传。 1)添加二维位置数据 打开 数据分析 -> 空间数据可视化 -> 二维数据 -> 添加,为上面演示的设备添加位置,刷新时间为1秒。在产品功能中,打开功能定义 ,在 标准功能 里,添加功能。 选择 其它类型 ,里面搜索 位置 ,在出现的列表中选一个(前面那几个都可以)。 笔者选择的是: 标识符:GeoLocation 适用类别:CuttingMachine 位置上传要设置的信息: 注意注意,如果选择的标准属性跟上图的类型定义不一样,需要手动修改。要把上面的位置属性按上图来改,有一个地方不同,都会失败。 当然,也可以一开始就按图手动创建。 2)基础代码 上传位置数据,不需要做什么大操作,按照属性的上传方法上传即可。模型代码参考: public class TestModel { public string id { get { return DateTime.Now.Ticks.ToString(); } set { } } public string version { get { return "1.0"; } set { } } public Params @params { get; set; } public TestModel() { @params = new Params(); } public class Params { public geoLocation GeoLocation { get; set; } public class geoLocation { public Value value { get; set; } public long time { get { return AliIoTClientJson.GetUnixTime(); } set { } } public geoLocation() { value = new Value(); } public class Value { public double Longitude { get; set; } public double Latitude { get; set; } public double Altitude { get; set; } public int CoordinateSystem { get; set; } } } public Params() { GeoLocation = new geoLocation(); } } public string method { get { return "thing.event.property.post"; } set { } } } 整体代码参考:定义位置模型 -> 设置位置数据 -> 上传位置数据 class Program { static AliIoTClientJson client; static void Main(string[] args) { // 创建客户端 client = new AliIoTClientJson(new DeviceOptions { ProductKey = "a1A6VVt72pD", DeviceName = "json", DeviceSecret = "7QrjTptQYCdepjbQvSoqkuygic2051zM", RegionId = "cn-shanghai" }); client.OpenPropertyDownPost(); // 设置要订阅的Topic、运行接收内容的Topic string[] topics = new string[] { client.CombineHeadTopic("get") }; // 使用默认事件 client.UseDefaultEventHandler(); // 连接服务器 client.ConnectIoT(topics, null, 60); while (true) { ToServer(); Thread.Sleep(1000); } Console.ReadKey(); } public static void ToServer() { // 实例化模型 TestModel model = new TestModel(); // 设置属性值 // 经度 model.@params.GeoLocation.value.Longitude = 113.952981; // 纬度 model.@params.GeoLocation.value.Latitude = 22.539843; // 海拔 model.@params.GeoLocation.value.Altitude = 56; // 坐标系类型 model.@params.GeoLocation.value.CoordinateSystem = 2; // 上传属性数据 client.Thing_Property_Post<TestModel>(model, false); } public class TestModel { public string id { get { return DateTime.Now.Ticks.ToString(); } set { } } public string version { get { return "1.0"; } set { } } public Params @params { get; set; } public TestModel() { @params = new Params(); } public class Params { public geoLocation GeoLocation { get; set; } public class geoLocation { public Value value { get; set; } public long time { get { return AliIoTClientJson.GetUnixTime(); } set { } } public geoLocation() { value = new Value(); } public class Value { public double Longitude { get; set; } public double Latitude { get; set; } public double Altitude { get; set; } public int CoordinateSystem { get; set; } } } public Params() { GeoLocation = new geoLocation(); } } public string method { get { return "thing.event.property.post"; } set { } } } 上面使用的是模拟位置数据,请实际情况设置位置数据。 打开阿里云物联网控制台 -> 数据分析 -> 空间数据可视化 -> 二维数据 -> 演示产品 会看到定位到了深圳阿里云大厦(高新园地铁站附近)~~~

优秀的个人博客,低调大师

阿里云物联网 .NET Core 客户端 | CZGL.AliIoTClient:6. 设备事件上报

根据阿里云物联网普通的定义,事件上报有 信息、告警、故障三种类型,事件是设备上传的消息通知,应当及时处理。 1)定义事件 打开阿里云物联网控制台,进入产品,点击 自定义功能 ,添加一个事件。 2)上传事件的方法 CZGL.AliIoTClient 中,有四个上传事件的方法 public int Thing_Event_Post(string eventName, string content, [bool isToLower = True]) public int Thing_Event_Post(string eventName, string content, [bool isToLower = True], [System.Text.Encoding encoding = null]) public int Thing_Event_Post<TModel>(TModel model, string eventName, [bool isToLower = True]) public int Thing_Event_Post<TModel>(TModel model, string eventName, [bool isToLower = True], [System.Text.Encoding encoding = null]) eventName: 事件的名称,即标识符。 content: Alink json 内容isToLower:是否转为小写encoding: 自定义上传 Alink json 的编码model: 事件的模型 第一种方法需要手动编写好 json,然后通过方法上传。第二种方法在第一种方法的基础上允许自定义字符编码。第三种、第四种是传入模型,由 CZGL.AliIoTClient 处理好再上传。 3)编写事件模型 每次只能上传一个事件,一个事件对应一个 模型 或 Alink json。 在 CZGL.AliIoTClient 中,你每次上传一个事件时,都需要设置此事件的名称。 根据上面在阿里云物联网控制台定义的事件,编写模型。 预览要生成的 Alink json : { "id": "123", "version": "1.0", "params": { "value": { "temperature":100.1 }, "time": 1524448722000 }, "method": "thing.event.cpuerror.post" } 对应模型如下: public class Cpuerror { public Cpuerror() { @params = new Params(); } public string id { get { return DateTime.Now.Ticks.ToString(); } set { } } public string version { get { return "1.0"; } set { } } public Params @params { get; set; } public class Params { public Params() { value = new Value(); } public Value value { get; set; } public long time { get { return AliIoTClientJson.GetUnixTime(); } set { } } public class Value { public float temperature { get; set; } } } public string @method { get { return "thing.event.cpuerror.post"; } set { } } } 一个事件对应一个类,如果事件里有多个输出参数,则在 Value 里定义好。 { ... ... public class Value { public float temperature { get; set; } /* *定义多个输出参数 */ } ... ... } 上报事件: Cpuerror cpuerror = new Cpuerror(); cpuerror.@params.value.temperature = 100.1F; client.Thing_Event_Post<Cpuerror>(cpuerror, "cpuerror", false); 4)容错上传事件的 Alink json 可以 容错 ,这给我们编写代码时带来了方便。、 例如将上面上传事件的代码改一下: public class Cpuerror { public string name = "cpuerror"; public Cpuerror() { @params = new Params(); } public string id { get { return DateTime.Now.Ticks.ToString(); } set { } } public string version { get { return "1.0"; } set { } } public Params @params { get; set; } public class Params { public Params() { value = new Value(); } public Value value { get; set; } public long time { get { return AliIoTClientJson.GetUnixTime(); } set { } } public class Value { public float temperature { get; set; } } } public string @method { get { return $"thing.event.{name}.post"; } set { } } } Cpuerror cpuerror = new Cpuerror(); cpuerror.@params.value.temperature = 100.2F; client.Thing_Event_Post<Cpuerror>(cpuerror, cpuerror.name, false); 对于 消息ID 等是必不可少的,“可多不可少”,其它无关字段可以增加上去,不会影响到上传和使用,例如上面的例子增加了一个 name 属性。 5)补充说明

优秀的个人博客,低调大师

阿里云物联网 .NET Core 客户端 | CZGL.AliIoTClient:8. 委托事件

CZGL.AliIoTClient 里设置了 7 个委托事件,在程序的不不同生命周期触发。 1)7个委托事件 /// <summary> /// 服务器属性设置 /// </summary> public PublishPropertyEventHandler PubPropertyEventHandler; /// <summary> /// 服务调用 /// </summary> public PublishServiceEventHandler PubServiceEventHandler; /// <summary> /// 收到其它Topic时触发 /// </summary> public PublishCommonEventHandler PubCommonEventHandler; /// <summary> /// 当 QOS=1或2时,收到订阅触发 /// </summary> public uPLibrary.Networking.M2Mqtt.MqttClient.MqttMsgPublishedEventHandler PubedEventHandler; /// <summary> /// 向服务器发布 Topic 时 /// </summary> public uPLibrary.Networking.M2Mqtt.MqttClient.MqttMsgSubscribedEventHandler SubedEventHandler; /// <summary> /// 向服务器发布 Topic 失败时 /// </summary> public uPLibrary.Networking.M2Mqtt.MqttClient.MqttMsgUnsubscribedEventHandler UnSubedEventHandler; /// <summary> /// 断开连接时 /// </summary> public uPLibrary.Networking.M2Mqtt.MqttClient.ConnectionClosedEventHandler ConnectionClosedEventHandler; 使用方法 public static void TestEvent(object sender, MqttMsgPublishEventArgs e) { { // handle message received string topic = e.Topic; string message = Encoding.ASCII.GetString(e.Message); Console.WriteLine("- - - - - - - - - - "); Console.WriteLine("get topic message,Date: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("topic: " + topic); Console.WriteLine("get messgae :\n" + message); } client.PubPropertyEventHandler += TestEvent; 这里是旧版本的文档,可以参考一下。 https://www.cnblogs.com/whuanle/p/10786991.html

优秀的个人博客,低调大师

2.1命令行和JSON的配置「深入浅出ASP.NET Core系列」

希望给你3-5分钟的碎片化学习,可能是坐地铁、等公交,积少成多,水滴石穿,谢谢关注。 命令行配置 1.新建控制台项目 2.nuget引入microsoft.aspnetcore.all 这里要注意版本号必须和dotnetcore兼容 3.编码 3.1.引入Microsoft.Extensions.Configuration; 3.2.AddCommandLine() 添加到命令行 3.3.AddInMemoryCollection 添加到内存当中 3.4.代替string.format的新语法糖:$"age:{configuration["age"]}" 4.查看结果 直接运行 powershell下运行 JSON配置 2.1新建配置文件student.json 编写json配置内容 2.2引入json,AddJsonFile() 2.3确保json文件生成到bin目录下 右键进入文件属性 设置始终复制和生成操作为内容 2.4编码读取配置 我是.NET架构师张飞洪,入行10年有余,人不堪其忧,吾不改其乐,谢谢您关注我的头条号。

优秀的个人博客,低调大师

(4)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Consul服务发现和消费

上一章说了 Consul服务注册 现在我要连接上Consul里面的服务 请求它们的API接口 应该怎么做呢? 1.找Consul要一台你需要的服务器 1.1 获取Consul下的所有注册的服务 using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500"))) { var services = consulClient.Agent.Services().Result.Response; foreach(var service in services.Values) { Console.WriteLine($"id={service.ID},name={service.Service},ip={service.Address},port={service.Port}"); } } 1.2 随机取一个Name为MsgService的服务 下面的代码使用当前 TickCount 进行取模的方式达到随机获取一台服务器实例的效果,这叫做“客户端负载均衡”: using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500"))) { var services = consulClient.Agent.Services().Result.Response.Values.Where(s => s.Service.Equals("MsgService", StringComparison.OrdinalIgnoreCase)); if(!services.Any()) { Console.WriteLine("找不到服务的实例"); } else { var service = services.ElementAt(Environment.TickCount%services.Count()); Console.WriteLine($"{service.Address}:{service.Port}"); } } 当然在一个毫秒之类会所有请求都压给一台服务器,基本就够用了。也可以自己写随机、轮询等客户端负载均衡算法,也可以自己实现按不同权重分配(注册时候 Tags 带上配置、权重等信息)等算法。 2.请求服务器的接口 你拿到了http地址 难道还不会请求接口么 找个httphelper 直接请求就好了 如果还是不会 就来群里问吧 群号:608188505 给大家上一个 我常用的httphelper 可能被我该的不像样了 不过相信大家都会用 不会的话 来群里找我吧。 1 using System; 2 using System.Collections.Generic; 3 using System.Diagnostics; 4 using System.IO; 5 using System.IO.Compression; 6 using System.Linq; 7 using System.Net; 8 using System.Net.Security; 9 using System.Runtime.InteropServices; 10 using System.Security.Cryptography.X509Certificates; 11 using System.Text; 12 using System.Text.RegularExpressions; 13 using System.Threading.Tasks; 14 15 namespace ClientApp 16 {/// <summary> 17 /// Http连接操作帮助类 18 /// </summary> 19 public class HttpHelper 20 { 21 private const int ConnectionLimit = 100; 22 //编码 23 private Encoding _encoding = Encoding.Default; 24 //浏览器类型 25 private string[] _useragents = new string[]{ 26 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36", 27 "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)", 28 "Mozilla/5.0 (Windows NT 6.1; rv:36.0) Gecko/20100101 Firefox/36.0", 29 "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0" 30 }; 31 32 private String _useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"; 33 //接受类型 34 private String _accept = "text/html, application/xhtml+xml, application/xml, */*"; 35 //超时时间 36 private int _timeout = 30 * 1000; 37 //类型 38 private string _contenttype = "application/x-www-form-urlencoded"; 39 //cookies 40 private String _cookies = ""; 41 //cookies 42 private CookieCollection _cookiecollection; 43 //custom heads 44 private Dictionary<string, string> _headers = new Dictionary<string, string>(); 45 46 public HttpHelper() 47 { 48 _headers.Clear(); 49 //随机一个useragent 50 _useragent = _useragents[new Random().Next(0, _useragents.Length)]; 51 //解决性能问题? 52 ServicePointManager.DefaultConnectionLimit = ConnectionLimit; 53 } 54 55 public void InitCookie() 56 { 57 _cookies = ""; 58 _cookiecollection = null; 59 _headers.Clear(); 60 } 61 62 /// <summary> 63 /// 设置当前编码 64 /// </summary> 65 /// <param name="en"></param> 66 public void SetEncoding(Encoding en) 67 { 68 _encoding = en; 69 } 70 71 /// <summary> 72 /// 设置UserAgent 73 /// </summary> 74 /// <param name="ua"></param> 75 public void SetUserAgent(String ua) 76 { 77 _useragent = ua; 78 } 79 80 public void RandUserAgent() 81 { 82 _useragent = _useragents[new Random().Next(0, _useragents.Length)]; 83 } 84 85 public void SetCookiesString(string c) 86 { 87 _cookies = c; 88 } 89 90 /// <summary> 91 /// 设置超时时间 92 /// </summary> 93 /// <param name="sec"></param> 94 public void SetTimeOut(int msec) 95 { 96 _timeout = msec; 97 } 98 99 public void SetContentType(String type) 100 { 101 _contenttype = type; 102 } 103 104 public void SetAccept(String accept) 105 { 106 _accept = accept; 107 } 108 109 /// <summary> 110 /// 添加自定义头 111 /// </summary> 112 /// <param name="key"></param> 113 /// <param name="ctx"></param> 114 public void AddHeader(String key, String ctx) 115 { 116 //_headers.Add(key,ctx); 117 _headers[key] = ctx; 118 } 119 120 /// <summary> 121 /// 清空自定义头 122 /// </summary> 123 public void ClearHeader() 124 { 125 _headers.Clear(); 126 } 127 128 /// <summary> 129 /// 获取HTTP返回的内容 130 /// </summary> 131 /// <param name="response"></param> 132 /// <returns></returns> 133 private String GetStringFromResponse(HttpWebResponse response) 134 { 135 String html = ""; 136 try 137 { 138 Stream stream = response.GetResponseStream(); 139 StreamReader sr = new StreamReader(stream, Encoding.UTF8); 140 html = sr.ReadToEnd(); 141 142 sr.Close(); 143 stream.Close(); 144 } 145 catch (Exception e) 146 { 147 Trace.WriteLine("GetStringFromResponse Error: " + e.Message); 148 } 149 150 return html; 151 } 152 153 /// <summary> 154 /// 检测证书 155 /// </summary> 156 /// <param name="sender"></param> 157 /// <param name="certificate"></param> 158 /// <param name="chain"></param> 159 /// <param name="errors"></param> 160 /// <returns></returns> 161 private bool CheckCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 162 { 163 return true; 164 } 165 166 /// <summary> 167 /// 发送GET请求 168 /// </summary> 169 /// <param name="url"></param> 170 /// <returns></returns> 171 public String HttpGet(String url) 172 { 173 return HttpGet(url, url); 174 } 175 176 177 /// <summary> 178 /// 发送GET请求 179 /// </summary> 180 /// <param name="url"></param> 181 /// <param name="refer"></param> 182 /// <returns></returns> 183 public String HttpGet(String url, String refer) 184 { 185 String html; 186 try 187 { 188 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckCertificate); 189 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 190 request.UserAgent = _useragent; 191 request.Timeout = _timeout; 192 request.ContentType = _contenttype; 193 request.Accept = _accept; 194 request.Method = "GET"; 195 request.Referer = refer; 196 request.KeepAlive = true; 197 request.AllowAutoRedirect = true; 198 request.UnsafeAuthenticatedConnectionSharing = true; 199 request.CookieContainer = new CookieContainer(); 200 //据说能提高性能 201 //request.Proxy = null; 202 if (_cookiecollection != null) 203 { 204 foreach (Cookie c in _cookiecollection) 205 { 206 c.Domain = request.Host; 207 } 208 209 request.CookieContainer.Add(_cookiecollection); 210 } 211 212 foreach (KeyValuePair<String, String> hd in _headers) 213 { 214 request.Headers[hd.Key] = hd.Value; 215 } 216 217 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 218 html = GetStringFromResponse(response); 219 if (request.CookieContainer != null) 220 { 221 response.Cookies = request.CookieContainer.GetCookies(request.RequestUri); 222 } 223 224 if (response.Cookies != null) 225 { 226 _cookiecollection = response.Cookies; 227 } 228 if (response.Headers["Set-Cookie"] != null) 229 { 230 string tmpcookie = response.Headers["Set-Cookie"]; 231 _cookiecollection.Add(ConvertCookieString(tmpcookie)); 232 } 233 234 response.Close(); 235 return html; 236 } 237 catch (Exception e) 238 { 239 Trace.WriteLine("HttpGet Error: " + e.Message); 240 return String.Empty; 241 } 242 } 243 244 /// <summary> 245 /// 获取MINE文件 246 /// </summary> 247 /// <param name="url"></param> 248 /// <returns></returns> 249 public Byte[] HttpGetMine(String url) 250 { 251 Byte[] mine = null; 252 try 253 { 254 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckCertificate); 255 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 256 request.UserAgent = _useragent; 257 request.Timeout = _timeout; 258 request.ContentType = _contenttype; 259 request.Accept = _accept; 260 request.Method = "GET"; 261 request.Referer = url; 262 request.KeepAlive = true; 263 request.AllowAutoRedirect = true; 264 request.UnsafeAuthenticatedConnectionSharing = true; 265 request.CookieContainer = new CookieContainer(); 266 //据说能提高性能 267 request.Proxy = null; 268 if (_cookiecollection != null) 269 { 270 foreach (Cookie c in _cookiecollection) 271 c.Domain = request.Host; 272 request.CookieContainer.Add(_cookiecollection); 273 } 274 275 foreach (KeyValuePair<String, String> hd in _headers) 276 { 277 request.Headers[hd.Key] = hd.Value; 278 } 279 280 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 281 Stream stream = response.GetResponseStream(); 282 MemoryStream ms = new MemoryStream(); 283 284 byte[] b = new byte[1024]; 285 while (true) 286 { 287 int s = stream.Read(b, 0, b.Length); 288 ms.Write(b, 0, s); 289 if (s == 0 || s < b.Length) 290 { 291 break; 292 } 293 } 294 mine = ms.ToArray(); 295 ms.Close(); 296 297 if (request.CookieContainer != null) 298 { 299 response.Cookies = request.CookieContainer.GetCookies(request.RequestUri); 300 } 301 302 if (response.Cookies != null) 303 { 304 _cookiecollection = response.Cookies; 305 } 306 if (response.Headers["Set-Cookie"] != null) 307 { 308 _cookies = response.Headers["Set-Cookie"]; 309 } 310 311 stream.Close(); 312 stream.Dispose(); 313 response.Close(); 314 return mine; 315 } 316 catch (Exception e) 317 { 318 Trace.WriteLine("HttpGetMine Error: " + e.Message); 319 return null; 320 } 321 } 322 323 /// <summary> 324 /// 发送POST请求 325 /// </summary> 326 /// <param name="url"></param> 327 /// <param name="data"></param> 328 /// <returns></returns> 329 public String HttpPost(String url, String data) 330 { 331 return HttpPost(url, data, url,null); 332 } 333 334 /// <summary> 335 /// 发送POST请求 336 /// </summary> 337 /// <param name="url"></param> 338 /// <param name="data"></param> 339 /// <param name="refer"></param> 340 /// <returns></returns> 341 public String HttpPost(String url, String data, String refer,string cookie) 342 { 343 String html; 344 try 345 { 346 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckCertificate); 347 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 348 request.UserAgent = _useragent; 349 request.Timeout = _timeout; 350 request.Referer = refer; 351 request.ContentType = _contenttype; 352 request.Accept = _accept; 353 request.Method = "POST"; 354 request.KeepAlive = true; 355 request.AllowAutoRedirect = true; 356 357 request.CookieContainer = new CookieContainer(); 358 if (!string.IsNullOrEmpty(cookie)) 359 { 360 _cookiecollection = this.ConvertCookieString(cookie); 361 } 362 //据说能提高性能 363 request.Proxy = null; 364 365 if (_cookiecollection != null) 366 { 367 foreach (Cookie c in _cookiecollection) 368 { 369 c.Domain = request.Host; 370 if (c.Domain.IndexOf(':') > 0) 371 c.Domain = c.Domain.Remove(c.Domain.IndexOf(':')); 372 } 373 request.CookieContainer.Add(_cookiecollection); 374 } 375 376 foreach (KeyValuePair<String, String> hd in _headers) 377 { 378 request.Headers[hd.Key] = hd.Value; 379 } 380 byte[] buffer = _encoding.GetBytes(data.Trim()); 381 request.ContentLength = buffer.Length; 382 request.GetRequestStream().Write(buffer, 0, buffer.Length); 383 request.GetRequestStream().Close(); 384 385 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 386 html = GetStringFromResponse(response); 387 if (request.CookieContainer != null) 388 { 389 response.Cookies = request.CookieContainer.GetCookies(request.RequestUri); 390 } 391 if (response.Cookies != null) 392 { 393 _cookiecollection = response.Cookies; 394 } 395 if (response.Headers["Set-Cookie"] != null) 396 { 397 string tmpcookie = response.Headers["Set-Cookie"]; 398 _cookiecollection.Add(ConvertCookieString(tmpcookie)); 399 } 400 401 response.Close(); 402 return html; 403 } 404 catch (Exception e) 405 { 406 Trace.WriteLine("HttpPost Error: " + e.Message); 407 return String.Empty; 408 } 409 } 410 411 412 public string UrlEncode(string str) 413 { 414 StringBuilder sb = new StringBuilder(); 415 byte[] byStr = _encoding.GetBytes(str); 416 for (int i = 0; i < byStr.Length; i++) 417 { 418 sb.Append(@"%" + Convert.ToString(byStr[i], 16)); 419 } 420 421 return (sb.ToString()); 422 } 423 424 /// <summary> 425 /// 转换cookie字符串到CookieCollection 426 /// </summary> 427 /// <param name="ck"></param> 428 /// <returns></returns> 429 private CookieCollection ConvertCookieString(string ck) 430 { 431 CookieCollection cc = new CookieCollection(); 432 string[] cookiesarray = ck.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 433 for (int i = 0; i < cookiesarray.Length; i++) 434 { 435 string[] cookiesarray_2 = cookiesarray[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 436 for (int j = 0; j < cookiesarray_2.Length; j++) 437 { 438 string[] cookiesarray_3 = cookiesarray_2[j].Trim().Split("=".ToCharArray()); 439 if (cookiesarray_3.Length == 2) 440 { 441 string cname = cookiesarray_3[0].Trim(); 442 string cvalue = cookiesarray_3[1].Trim(); 443 if (cname.ToLower() != "domain" && cname.ToLower() != "path" && cname.ToLower() != "expires") 444 { 445 Cookie c = new Cookie(cname, cvalue); 446 cc.Add(c); 447 } 448 } 449 } 450 } 451 452 return cc; 453 } 454 455 456 public void DebugCookies() 457 { 458 Trace.WriteLine("**********************BEGIN COOKIES*************************"); 459 foreach (Cookie c in _cookiecollection) 460 { 461 Trace.WriteLine(c.Name + "=" + c.Value); 462 Trace.WriteLine("Path=" + c.Path); 463 Trace.WriteLine("Domain=" + c.Domain); 464 } 465 Trace.WriteLine("**********************END COOKIES*************************"); 466 } 467 468 } 469 } Httphelper 小哥哥 小姐姐们 如果本篇文章对你们有帮助的话 就点点右下角的推荐吧 0.0 现在的努力只是为了更好的将来,将来你一定不会后悔你现在的努力。一起加油吧!!! C#/.NetCore技术交流群:608188505欢迎加群交流 如果您认为这篇文章还不错或者有所收获,您可以点击右下角的【推荐】按钮精神支持,因为这种支持是我继续写作,分享的最大动力!

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码