using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MVMoniter
{
    public class UdpLoggerReceiver
    {
        private UdpClient udpClient;
        private Thread receiveThread;
        public event Action<string> LogReceived;

        public UdpLoggerReceiver(int listenPort)
        {
            udpClient = new UdpClient(listenPort);
            receiveThread = new Thread(ReceiveLogs)
            {
                IsBackground = true
            };
            receiveThread.Start();
        }

        private void ReceiveLogs()
        {
            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                try
                {
                    byte[] data = udpClient.Receive(ref remoteEndPoint);
                    string message = Encoding.UTF8.GetString(data);
                    LogReceived?.Invoke(message); // 触发事件
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"日志接收失败: {ex.Message}");
                }
            }
        }

        public void Close()
        {
            udpClient?.Close();
            receiveThread?.Abort();
        }
        //-------------------------------------------------
    }
}
