using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using static FaceSdkX64Service.TH_Faces; namespace FaceSdkX64Service { public class HttpServer { private string ImgPath = string.Empty; HttpListener listener; public HttpServer(int port, string imgPath) { ImgPath = imgPath; listener = new HttpListener(); listener.Prefixes.Add($"http://+:{port}/"); listener.Start(); HttpListenerContext httpListenerContext = listener.GetContext(); GetConnect(httpListenerContext); listener.Stop(); //关闭HttpListener } private void GetConnect(HttpListenerContext context) { try { // 等待客户端连接 if (!context.Request.IsWebSocketRequest) { if (context == null) return; var request = context.Request; var response = context.Response; response.StatusCode = 200; response.ContentType = "text/plain; charset=utf-8"; response.Headers.Add("Access-Control-Allow-Origin", "*"); // 允许跨域访问 using (var stream = response.OutputStream) { // 把处理信息返回到客户端 if (string.IsNullOrEmpty(ImgPath)) { stream.Write(new byte[0], 0, 0); } else { string base64 = ImageToBase64(ImgPath); // 将图片转换为Base64字符串 byte[] buffer = Encoding.UTF8.GetBytes(base64); stream.Write(buffer, 0, buffer.Length); } } } } catch (Exception ex) { } } private string ImageToBase64(string imagePath) { try { byte[] imageBytes = System.IO.File.ReadAllBytes(imagePath); return Convert.ToBase64String(imageBytes); } catch (Exception ex) { return string.Empty; } } } }