1. 程式人生 > 其它 >WPF內嵌Http協議的Server端

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 }
View Code

服務啟動時需要啟動監聽,服務停止時需要停止監聽

 1     /// <summary>
 2     /// App.xaml 的互動邏輯
 3     /// </summary>
 4     public partial class App : Application
 5     {
 6         public App()
 7         {
 8             HttpServerService.Start();
 9         }
10     }
View Code

文章主要參考: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