HVideoManager.cs 6.6 KB
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using TSA_V.Common;

namespace TSA_V.DeviceLibrary
{
    public  class HVideoManager
    {

        //private static  int ServerPort = 8765;
        public   static string LastMsg = ""; 
        private  static HttpListener listener = null;
        private  static bool mStart = false;
        public static bool StartRun()
        {
            try
            { 
                if (Setting_NInit.Hand_ServerPort > 0)
                {
                    listener = new HttpListener();
                    listener.Prefixes.Add($"http://localhost:{Setting_NInit.Hand_ServerPort}/"); // 监听的URL地址
                    listener.Start();
                    LogUtil.info("HTTP服务已启动,正在监听9876端口...");
                    Task.Factory.StartNew(() =>
                    {
                           Run();
                    });
                }
                return true;

            }
            catch (Exception ex)
            {
                LogUtil.error("hVideoManager StartRun 出错:" + ex.ToString());
                return false;
            }
        }
        private static void Run() {
            mStart = true;
            while (mStart)
            {
                try
                {
                    // 等待请求连接
                    HttpListenerContext context = listener.GetContext();

                    // 获取请求对象和响应对象
                    HttpListenerRequest request = context.Request;
                    HttpListenerResponse response = context.Response;
                    try
                    {
                        // 处理指定路径和POST请求
                        if (request.HttpMethod == "POST" && request.Url.AbsolutePath == "/rest/api/v1/imgUpload")
                        {
                            // 读取POST数据
                            string postData;
                            using (StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
                            {
                                postData = reader.ReadToEnd();
                                //Console.WriteLine("收到POST请求数据:" + postData);
                            }
                            ServerOnReceived(request.Url.AbsolutePath, postData);
                            //// 将POST数据转换为字典
                            //NameValueCollection formData = ParseFormData(postData);

                            //// 获取inputText的值并保存
                            //string inputText = formData["inputText"];
                            //Console.WriteLine("获取到的inputText的值为:" + inputText);
                            //// 在这里进行保存操作
                            //// ...

                            // 返回响应
                            string responseString = "OK";
                            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                            response.ContentLength64 = buffer.Length;
                            response.OutputStream.Write(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            // 不支持其他请求方法或路径
                            response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                        }

                    }
                    catch (Exception e)
                    {
                        LogUtil.error("出错:" + e.ToString());
                    }
                    finally
                    {
                        // 关闭响应流
                        response.Close();
                    } 
                }
                catch (Exception ex)
                {
                    LogUtil.error("出错:" + ex.ToString());
                }

            }
        }


        public static void StopRun()
        {
            try
            {
                mStart = false;
                Thread.Sleep(100);
                listener.Stop();
            }
            catch (Exception ex)
            {
                LogUtil.error("出错:" + ex.ToString());
            }
        }

        private  static string ImgUpload = "/rest/api/v1/imgUpload";
        private static string ServerOnReceived(string reqPath, string paramStr)
        {
            if (paramStr == "" || reqPath=="")
            {
                return "";
            }
            //LogUtil.info("ServerOnReceived [" + reqPath + "] [" + paramStr + "] ");
            //paramStr = paramStr.Replace("%23", "#");
            try
            {
                Dictionary<string, string> paramMap = JsonHelper.DeserializeJsonToObject< Dictionary<string, string>>(paramStr);
                if (reqPath.Equals(ImgUpload))
                {
                   bool result=paramMap.TryGetValue("input", out string imgStr);
                    if (result)
                    {
                        LastMsg = imgStr;
                    } 
                }

                else
                {
                    //LogUtil.info("[" + reqPath + "]没有相关处理");
                    return "[" + reqPath + "]没有相关处理";
                }
                return "OK";
            }
            catch (Exception ex)
            {
                LogUtil.info("[" + reqPath + "][" + paramStr + "]处理错误:" + ex.ToString());
                return "Error";
            }
        } 


        private static Bitmap Base64StringToImage(string inputStr)
        {
            try
            {
                if (inputStr == "")
                {
                    return null ;
                }
                byte[] arr = Convert.FromBase64String(inputStr);
                using (MemoryStream ms = new MemoryStream(arr))
                {
                    Bitmap bmp = new Bitmap(ms);
                    ms.Close();
                    return bmp;
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("Base64StringToImage 转换失败/nException:" +ex.ToString());
                return null;
            }
        }

        public static Bitmap GetLastImg( )
        {
            string inputStr = LastMsg; 
            if (LastMsg != "")
            {
                return Base64StringToImage(inputStr);
            }
            return null;
        }

    }
}