yanjinhui
2025-06-09 ac93c4092a21dbf0fa9cf8b9b1302f2d5d183f61
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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;
            }
        }
    }
}