在某些情況下,如使用WPF、WinForm或Windows服務開發(fā)的程序,可能需要提供接口以便第三方服務主動與其通信,并進行服務調用和數(shù)據(jù)推送,你想到哪些簡單的方式快速實現(xiàn)?
想到的部分實現(xiàn)方式有以下幾種:
Web服務:使用Web服務(如RESTful API)可以使得第三方服務通過HTTP協(xié)議與你的程序通信。在WPF和WinForm中,可以使用ASP.NET Web API或ASP.NET Core Web API來實現(xiàn)接口邏輯。在Windows服務中,可以使用相應的框架(如Topshelf)來實現(xiàn)接口邏輯。
消息隊列:使用消息隊列(如RabbitMQ、Kafka)可以使得第三方服務通過異步消息傳遞與你的程序通信。這樣可以提高程序的可靠性和擴展性,避免因為第三方服務的延遲或故障導致程序出現(xiàn)問題。
RPC(Remote Procedure Call):使用RPC可以使得第三方服務像調用本地函數(shù)一樣調用你的程序提供的接口。常見的RPC框架包括gRPC、Apache Thrift等。
Socket編程:使用Socket編程可以使得第三方服務與你的程序建立長連接,進行實時通信。這種方式適合需要高頻率交互的場景,但需要考慮網絡穩(wěn)定性和安全性等問題。
其他方式:根據(jù)具體業(yè)務需求,還可以使用其他方式來實現(xiàn)接口的提供,如使用FTP、SMTP等協(xié)議進行文件傳輸和郵件推送等。
本文就是采用一種非常簡單的方式來對外提供接口,代碼很簡單就是使用.net里的System.Net命名空間下的HttpListener就可以實現(xiàn)Http協(xié)議的Server端。
HttpListener 是 .NET Framework 提供的一個類,用于創(chuàng)建基于 HTTP 協(xié)議的服務器。它可以在本地監(jiān)聽指定的 IP 地址和端口號,并接收來自客戶端的 HTTP 請求。HttpListener 可以用于各種場景,包括但不限于以下幾個方面:
Web API:可以使用 HttpListener 創(chuàng)建自己的 Web API 服務,接收客戶端的 HTTP 請求,并根據(jù)請求內容進行相應的處理和響應。這對于需要輕量級的、自定義的 Web 服務非常有用,尤其是在沒有使用 ASP.NET 或其他 Web 框架的情況下。
嵌入式 Web 服務器:如果應用程序需要內置一個簡單的 Web 服務器,以提供靜態(tài)文件或動態(tài)內容,那么可以使用 HttpListener。例如,你可以將 HTML、CSS、JavaScript 文件作為靜態(tài)資源提供給客戶端,或者根據(jù)客戶端請求生成動態(tài)的 HTML 頁面。
反向代理:HttpListener 還可以用于創(chuàng)建反向代理服務器。通過監(jiān)聽指定的端口,將客戶端的請求轉發(fā)到不同的后端服務器上,并將后端服務器的響應返回給客戶端。這在構建高性能、負載均衡的 Web 服務器集群時非常有用。
測試和調試:在開發(fā)和調試階段,可以使用 HttpListener 模擬一個簡單的 HTTP 服務器,以接收和處理來自客戶端的請求。這樣可以方便地測試和調試應用程序,而無需依賴于外部的 Web 服務器。
注意事項:使用 HttpListener 創(chuàng)建的服務器通常是基于 HTTP 協(xié)議的,因此它適用于與客戶端之間進行 HTTP 通信的場景。對于其他協(xié)議(如 TCP、UDP 等),可能需要使用不同的技術和類庫來實現(xiàn)。此外,使用 HttpListener 創(chuàng)建的服務器通常是單線程的,因此在高并發(fā)的情況下,可能需要進行性能優(yōu)化或考慮使用其他技術來提高并發(fā)處理能力。
官網的示例代碼
下面是服務端一個實現(xiàn)代碼:
using Newtonsoft.Json;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Text;using System.Threading.Tasks;namespace CustomHttpServer{ public class HttpServerService { private static bool isExcute = true; private static HttpListener listener = new HttpListener(); public static void Start() { //單獨開啟一個線程執(zhí)行監(jiān)聽消息 System.Threading.ThreadPool.QueueUserWorkItem(w => Excute()); } private static void Excute() { if (HttpListener.IsSupported) { if (!listener.IsListening) { //添加需要監(jiān)聽的url listener.Prefixes.Add("http://127.0.0.1:8888/"); //開始監(jiān)聽端口,接收客戶端請求 listener.Start(); } while (isExcute) { try { //阻塞主函數(shù)至接收到一個客戶端請求為止 等待請求 HttpListenerContext context = listener.GetContext(); //解析請求 HttpListenerRequest request = context.Request; //構造響應 HttpListenerResponse response = context.Response; string httpMethod = request.HttpMethod?.ToLower(); string rawUrl = request.RawUrl; var Url = request.Url; if (httpMethod == "get") { //獲取查詢參數(shù) var queryString = request.QueryString; //TODO 其他操作 } else if (httpMethod == "post") { // TODO 處理請求體數(shù)據(jù) var reader = new StreamReader(request.InputStream); var questBody = reader.ReadToEnd(); if (!string.IsNullOrEmpty(rawUrl)) { //TODO 反序列化RequestBody,調用其他業(yè)務 } } var responseString = string.Empty; responseString = JsonConvert.SerializeObject(new { code = 1, msg = "發(fā)送成功" }); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); //對客戶端輸出相應信息. response.ContentLength64 = buffer.Length; //發(fā)送響應 using (System.IO.Stream output = response.OutputStream) { output.Write(buffer, 0, buffer.Length); } } catch (Exception exceotion) { string str = exceotion.Message; } } } else { // TODO 系統(tǒng)不支持HttpListener } } public static void Stop() { isExcute = false; if (listener.IsListening) listener.Stop(); } }}
WPF客戶端調用:
/// <summary> /// App.xaml 的交互邏輯 /// </summary> public partial class App : Application { public App() { HttpServerService.Start(); } }
Windows服務調用:
protected override void OnStart(string[] args){ HttpServerService.Start();}protected override void OnStop(){ //停止監(jiān)聽 HttpServerService.Stop();}
作為文件服務器的應用。
using System;using System.IO;using System.Net;namespace FileServerDemo{ public class FileServer { private static FileServer _instance; private HttpListener _listener; private string _rootDirectory; private FileServer() { _rootDirectory = @"C:/Files/"; // 指定文件根目錄 } public static FileServer Instance { get { if (_instance == null) { _instance = new FileServer(); } return _instance; } } public void Start() { if (_listener != null && _listener.IsListening) { throw new InvalidOperationException("File server is already running."); } string url = "http://localhost:8080/"; try { _listener = new HttpListener(); _listener.Prefixes.Add(url); _listener.Start(); Console.WriteLine($"File Server is running. Listening on {url}"); while (true) { HttpListenerContext context = _listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; string filePath = Path.Combine(_rootDirectory, request.Url.LocalPath.TrimStart('/')); if (File.Exists(filePath)) { byte[] buffer = File.ReadAllBytes(filePath); response.ContentType = GetContentType(filePath); response.ContentLength64 = buffer.Length; response.OutputStream.Write(buffer, 0, buffer.Length); response.OutputStream.Close(); } else { response.StatusCode = (int)HttpStatusCode.NotFound; response.Close(); } } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } public void Stop() { if (_listener != null && _listener.IsListening) { _listener.Stop(); _listener.Close(); _listener = null; Console.WriteLine("File Server stopped."); } } private string GetContentType(string filePath) { string extension = Path.GetExtension(filePath).ToLower(); switch (extension) { case ".txt": return "text/plain"; case ".html": return "text/html"; case ".css": return "text/css"; case ".js": return "application/javascript"; case ".jpg": case ".jpeg": return "image/jpeg"; case ".png": return "image/png"; default: return "application/octet-stream"; } } }}
在上述示例代碼中,我們展示了如何使用 HttpListener 類構建一個簡單的文件服務器。通過監(jiān)聽指定的 URL,并在接收到請求時返回對應的文件內容,我們可以實現(xiàn)一個基本的文件服務功能。
總之,HttpListener是一個強大而靈活的類,可以用于創(chuàng)建基于HTTP協(xié)議的服務器應用程序。它提供了豐富的功能和靈活的配置選項,能夠輕松地處理HTTP請求和響應。通過深入了解HttpListener的用法和特性,就可以更好地利用它的優(yōu)勢,來提供高效、可靠的網絡服務。因此,如果您正在開發(fā)基于HTTP的應用程序,不妨考慮使用HttpListener來實現(xiàn)您的需求。
本文鏈接:http://www.www897cc.com/showinfo-26-75296-0.html了解HttpListener:用于創(chuàng)建基于HTTP協(xié)議的桌面&Web應用程序
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com