WPF内嵌Http协议的Server端
需求:有时后比如WPF,WinForm,Windows服务这些程序可能需要对外提供接口用于第三方服务主动通信,调用推送一些服务或者数据。
想到的部分实现方式:
一、使用Socket/WebSocket通信
二、使用消息队列(比如rabbitmq)
三、使用RPC框架(比如gRPC)
四、使用http协议的方式
五、当然也可以使用数据库或者本地文件等形式实现不过这种太不好了
本文就是采用第四种对外提供接口,代码很简单就是使用.net里的System.Net命名空间下的HttpListener就可以实现Http协议的Server端
下面是服务端一个实现代码

1 using Newtonsoft.Json;
2 using System;
3 using System.Collections.Generic;
4 using System.IO;
5 using System.Linq;
6 using System.Net;
7 using System.Text;
8 using System.Threading.Tasks;
9
10 namespace WpfHttpServer
11 {
12 public class HttpServerService
13 {
14 private static bool isExcute = true;
15 private static HttpListener listener = new HttpListener();
16 public static void Start()
17 {
18 System.Threading.ThreadPool.QueueUserWorkItem(w => Excute());//单独开启一个线程执行监听消息
19 }
20
21 private static void Excute()
22 {
23 if (HttpListener.IsSupported)
24 {
25 if (!listener.IsListening)
26 {
27 listener.Prefixes.Add("http://127.0.0.1:8888/"); //添加需要监听的url
28 listener.Start(); //开始监听端口,接收客户端请求
29 }
30 while (isExcute)
31 {
32 try
33 {
34 //阻塞主函数至接收到一个客户端请求为止 等待请求
35 HttpListenerContext context = listener.GetContext();
36 //解析请求
37 HttpListenerRequest request = context.Request;
38 //构造响应
39 HttpListenerResponse response = context.Response;
40 //http请求方式:get,post等等
41 string httpMethod = request.HttpMethod?.ToLower();
42 string rawUrl = request.RawUrl;//不包括IP和端口
43 var Url = request.Url;//全路径
44
45 if (httpMethod == "get")
46 {
47 //获取查询参数
48 var queryString = request.QueryString;
49 // 请求接口 test/method?id=5
50 //键值对方式 string val = queryString["key"];
51 //string val = queryString["id"];val的值是5
52 }
53 else if (httpMethod == "post")
54 {
55 //请求接口 test/postMethod 格式是json
56 //{
57 // "id":5,
58 // "name":"zs"
59 //}
60 //获取pots请求的请求体,json格式的字符串
61 var reader = new StreamReader(request.InputStream);
62 var questBody = reader.ReadToEnd();
63 if (!string.IsNullOrEmpty(rawUrl))
64 {
65 //这里可以直接用switch这个只是demo
66 if (rawUrl.Equals("/server/uploadgenconnected", StringComparison.OrdinalIgnoreCase))
67 {
68 if (!string.IsNullOrEmpty(questBody))
69 {
70 UploadGenConnectedModel model = JsonConvert.DeserializeObject<UploadGenConnectedModel>(questBody);
71 if (model != null)
72 {
73 // To Do
74 }
75 }
76
77 }
78 }
79 }
80
81 var responseString = string.Empty;
82
83 // 执行其他业务逻辑
84 //*****************
85
86 responseString = JsonConvert.SerializeObject(new { code = 1, msg = "发送成功" });
87 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
88 //对客户端输出相应信息.
89 response.ContentLength64 = buffer.Length;
90 //response.StatusCode = 200;
91 //response.ContentType = "text/plain";
92 //发送响应
93 using (System.IO.Stream output = response.OutputStream)
94 {
95 output.Write(buffer, 0, buffer.Length);
96 }
97 }
98 catch (Exception exceotion)
99 {
100 //Logger.Error("处理消息异常", exceotion);
101 string str = exceotion.Message;
102 }
103 }
104 }
105 else
106 {
107 //Logger.Info("系统不支持HttpListener");
108 }
109 }
110
111 public static void Stop()
112 {
113 isExcute = false;
114 if (listener.IsListening)
115 listener.Stop();
116 }
117
118 }
119
120 public class UploadGenConnectedModel
121 {
122 public bool GenConnected { get; set; }
123 }
124
125 }
服务启动时需要启动监听,服务停止时需要停止监听

1 /// <summary>
2 /// App.xaml 的交互逻辑
3 /// </summary>
4 public partial class App : Application
5 {
6 public App()
7 {
8 HttpServerService.Start();
9 }
10 }
文章主要参考:https://www.cnblogs.com/pudefu/p/9512326.html
粗略参考
https://www.cnblogs.com/uu102/archive/2013/02/16/2913410.html
https://www.cnblogs.com/tuyile006/p/11857590.html
https://www.cnblogs.com/GreenShade/p/10915023.html
https://blog.csdn.net/crystalcs2010/article/details/107937472
WPF内嵌Http协议的Server端的更多相关文章
- WPF内嵌代码和后台代码简单混合使用
下面实例展示了WPF内嵌代码和后台代码混合使用,一个简单基础的实例: xaml文件: <Window x:Class="WPF内嵌代码和后台代码混合使用.MainWindow" ...
- WPF内嵌WCF服务对外提供接口
要测试本帖子代码请记得管理员权限运行vs. 我写这个帖子的初衷是在我做surface小车的时候有类似的需求,感觉这个功能还挺有意思的,所以就分享给大家,网上有很多关于wcf的文章 我就不一一列举了.公 ...
- LoRaWAN协议(三)--Server端数据协议
LoRaWAN Server 端架构 LoRaWAN 的server包括 NS(Network server).AS(application server).CS(Custom server).... ...
- WPF内嵌网页的两种方式
在wpf程序中,有时会内嵌网页.内嵌网页有两种方法,一种是使用wpf自带WebBrowser控件来调用IE内核,另一种是使用CefSharp包来调用chrom内核. 一.第一种使用自带WebBrows ...
- WPF内嵌CEF控件,与JS交互
1)安装cefsharp.winform包 打开VS2017,打开nuget,找到cefsharp.winform,安装 问:为什么wpf程序不使用cefsharp.wpf? 答:因为cefwpf 4 ...
- Winform/WPF中内嵌BeetleX的HTTP服务
在新版本的BeetleX.FastHttpApi加入了对netstandard2.0支持,如果程序基于.NetFramework4.6.1来构建WinForm或WPF桌面程序的情况下可以直接把Beet ...
- 使用Chrome开发者工具调试Android端内网页(微信,QQ,UC,App内嵌页等)
使用Chrome开发者工具调试Android端内网页(微信,QQ,UC,App内嵌页等) 前言 移动端页面调试一直是好多朋友头疼的问题,iOS 由于其封闭的特性和整体较高的性能,整体适配相对好做,调试 ...
- WPF背景透明内嵌WebBrowser不显示问题,即AllowsTransparency = true 和 Webbrowser 等控件显示冲突
首先感谢两位先导者: 1. 解决 WPF AllowsTransparency = true 和 Webbrowser 等控件显示冲突 原文地址:https://www.cnblogs.com/zhi ...
- WPF应用程序内嵌网页
原文:WPF应用程序内嵌网页 版权声明:本文为博主原创文章,转载请注明出处. https://blog.csdn.net/shaynerain/article/details/78160984 WPF ...
- [Web Server]Tomcat调优之SpringBoot内嵌Tomcat源码分析
以springboot:2.3.12.RELEASE中内嵌的tomcat-embed-core:9.0.46为例,进行分析 1 概述 1.0 关键依赖包 spring-boot-autoconfigu ...
随机推荐
- MongoDB 占用CPU资源过高
情况如下 db.currentOp() 发现有全表扫描 将 Collscan 对应的 Collection 建索引 db.Table1.createIndex({"DataTime" ...
- 背景 | 基于 Transformers 的编码器-解码器模型
!pip install transformers==4.2.1 !pip install sentencepiece==0.1.95 Vaswani 等人在其名作 Attention is all ...
- Go--下载安装
下载包地址:https://go.dev/dl/ linux: 下载后上传实例解压 tar -xvf go1.19.8.linux-amd64.tar.gz -C /usr/local/ 创建工作目录 ...
- ldap sssd授权linux登录
业务系统越来越多,服务器也越来越多,本文主要是给企业用户减少账号密码管理难度的. 目的:使用ldap统一管理账号密码,实现单点登录linux. 一点废话,网上找了很多文章,看得云里雾里,搞了几天算是搞 ...
- Can‘t resolve ‘core-js/modules/es.symbol‘ in
https://blog.csdn.net/guoqing2016/article/details/108639300?utm_medium=distribute.pc_relevant.none-t ...
- 手把手实践教你删除项目当中无用的npm包
在公司中,我们大部分都是多人共同开发和长时间维护一个项目,但是有时候我们会发现有很多已经废弃的npm 包存在 package.json 中,我们想要删除,但是又不能盲目的删除?那么 depcheck ...
- Linux 文件目录配置及命令总结
前言 在Linux中,一切皆文件,而每一个文件和目录都是从根目录开始的 Linux文件目录的作用 /bin目录:用来存放二进制可执行命令的目录,用户常用的命令都存在该目录下. /sbin目录:用来存放 ...
- 面试官:Redis持久化能关吗?怎么关?
数据持久化是指将数据从内存中,保存到磁盘或其他持久存储介质的过程,这样做的目的是为了保证数据不丢失. 而 Redis 的持久化功能默认是开启的,这样做的目的也是为了保证程序的稳定性(防止缓存雪崩.缓存 ...
- JS - this 操作 dom , 添加样式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8 ...
- Go-快速排序
package main import "fmt" // 快速排序 // 特征: // 1. 选定一个数,让这个数左边的比这个数小,右边比这个数大 // 2. 然后这个基数就是已经 ...