winfrom 或wpf 提供http接口和websocket接口
1、新建winform项目
2、添加HTTP处理工具类

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace PrintTest { public class HttpServerHelper { private readonly string selfUrl;//客户端自身(也就是该程序本身)作为服务器,需要确认以自身哪个端口来对外监听外部的访问 private readonly HttpListener myListener; private readonly Dictionary<string, Func<HttpListenerContext, Task<string>>> myRoutes; //路由映射 //构造函数 //selfListenAddrs:实际给一个 http://ip:port/就行,不用搞太多端口区分 public HttpServerHelper(string[] selfListenAddrs) { if (!HttpListener.IsSupported) { throw new NotSupportedException("当前平台不支持HttpListener"); } myListener = new HttpListener();//初始化HttpListener实例 //初始化路由映射字典 myRoutes = new Dictionary<string, Func<HttpListenerContext, Task<string>>>();// //为服务器(就是自身)添加地址和端口 (实际) foreach (string addr in selfListenAddrs) { myListener.Prefixes.Add(addr); //内容格式http://ip:port/api/ } selfUrl = selfListenAddrs[0];//记录第一个监听的地址 } //判断监听实例是否在监听 public bool IsOpen { get { return myListener.IsListening; } } //启动服务器 public void Start() { myListener.Start(); myListener.BeginGetContext(ProcessRequestCallback, myListener);//处理客户端请求 } //停止服务器 public void Stop() { myListener.Stop(); myListener.Close(); } //添加路由和处理程序的映射关系 public void AddRoute(string route, Func<HttpListenerContext, Task<string>> handler) { myRoutes.Add(route, handler); } //处理客户端(即外部程序)发来请求的处理逻辑 (这里是定义的回调函数) private async void ProcessRequestCallback(IAsyncResult result) { HttpListener listener = (HttpListener)result.AsyncState; //开始下一个请求的监听 listener.BeginGetContext(ProcessRequestCallback, listener); try { HttpListenerContext context = listener.EndGetContext(result); //获取请求方法和URL路径 string httpMethod = context.Request.HttpMethod; string url = context.Request.Url.AbsolutePath; string responseString = "No Data!";//默认响应字符串 Func<HttpListenerContext, Task<string>> handler; //如果请求路径存在与路由映射中,执行相应的处理程序 if (myRoutes.TryGetValue(url, out handler)) { //获取处理程序返回的响应数据 responseString = await handler(context); //将响应数据编码成字节数组 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); //设置响应的内容长度和状态码 context.Response.ContentLength64 = buffer.Length; context.Response.StatusCode = (int)HttpStatusCode.OK; // 设置响应头中的 Content-Type 为 application/json 并指定字符编码为 UTF-8(修复浏览器访问GET请求时,反馈值中文乱码问题) context.Response.ContentType = "application/json; charset=utf-8"; //将响应写入输出流并关闭输出流 context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.OutputStream.Close(); } else { //如果请求不存在与路由映射中,返回404错误 context.Response.StatusCode = (int)HttpStatusCode.NotFound; context.Response.Close(); } } catch (Exception ex) { //Log4NetHelper.Error("HttpServerHelper.ProcessRequestCallback:" + ex.Message); } } } }
3、包管理工具安装 WebSocketSharp-netstandard ,版本1.0.1。
3、新增WebSocketServerManager

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebSocketSharp.Server; namespace TiJianUtil { public class WebSocketServerManager { private static WebSocketServer WebSocketServers = null; public static bool IsListening { get { if (WebSocketServers == null) return false; return WebSocketServers.IsListening; } } private static void Init() { WebSocketServers = new WebSocketServer(8888); //添加具有指定行为和路径的WebSocket服务 //string 参数 表示要添加的服务的绝对路径 WebSocketServers.AddWebSocketService<Laputa>("/Laputa"); } public static void Open() { WebSocketServers.Start(); Console.WriteLine("开启服务器"); } public static void Close() { WebSocketServers.Stop(); Console.WriteLine("关闭服务器"); } static WebSocketServerManager() { Init(); } private WebSocketServerManager() { } } }
4、新增Laputa

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebSocketSharp; using WebSocketSharp.Server; namespace TiJianUtil { public class Laputa : WebSocketBehavior { protected override void OnMessage(MessageEventArgs e) { Console.WriteLine("[OnMessage]" + e.Data); var msg = e.Data == "BALUS" ? "Are you kidding?" : "I'm not available now."; Send(msg); } protected override void OnOpen() { Console.WriteLine("[OnOpen]"); } protected override void OnClose(CloseEventArgs e) { Console.WriteLine("[OnClose]" + e.Reason); } protected override void OnError(ErrorEventArgs e) { Console.WriteLine("[OnError]" + e.Message); } } }
5、使用方式,在form1代码中

using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TiJianUtil { public partial class Form1 : Form { public Form1() { InitializeComponent(); IniHttpServer(); WebSocketServerManager.Open(); } /// <summary> /// 初始化HTTP服务 /// </summary> public static void IniHttpServer() { //注意:参数内的IP就是本机以后对外身份的ip(正式使用需要修改), 参数内的端口就是本机对外接受“接口”访问的端口 HttpServerHelper httpServer = new HttpServerHelper(new string[] { "http://127.0.0.1:1314/" }); httpServer.AddRoute("/reader/readcard", ReadCard); httpServer.Start(); } /// <summary> /// 身份证读卡 /// </summary> /// <param name="context"></param> /// <returns></returns> public static async Task<string> ReadCard(HttpListenerContext context) { string httpMethod = context.Request.HttpMethod; string responseString = ""; if (httpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) { // 处理 POST 请求 if (context.Request.HasEntityBody) { using (Stream body = context.Request.InputStream) { using (StreamReader reader = new StreamReader(body, context.Request.ContentEncoding)) { string postData = await reader.ReadToEndAsync(); // 读取 POST 数据 responseString = "{\"code\":\"200\",\"message\":\"处理成功\"}";//后面根据实际约定进行定义 } } } } return responseString; } } }
6、websocket客户端

<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <script type="text/javascript"> function WebSocketTest() { if ("WebSocket" in window) { alert("您的浏览器支持 WebSocket!"); // 打开一个 web socket var ws = new WebSocket("ws://localhost:8888/Laputa"); ws.onopen = function() { // Web Socket 已连接上,使用 send() 方法发送数据 ws.send("我是发送的数据"); }; ws.onmessage = function (evt) { var received_msg = evt.data; }; ws.onclose = function() { // 关闭 websocket alert("连接已关闭..."); }; } else { // 浏览器不支持 WebSocket alert("您的浏览器不支持 WebSocket!"); } } </script> </head> <body> <div id="sse"> <a href="javascript:WebSocketTest()">运行 WebSocket</a> </div> </body> </html>
本文来自博客园,作者:Rolay,转载请注明原文链接:https://www.cnblogs.com/rolayblog/p/18778323