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

namespace MVMoniter
{
    public class UdpReceiver
    {
        private readonly UdpClient udpClient;
        private readonly string ipAddress;
        private readonly int port;
        private bool isReceiving;

        public event EventHandler<string> OnMessageReceived;

        public UdpReceiver(string ipAddress, int port)
        {
            this.ipAddress = ipAddress;
            this.port = port;
            udpClient = new UdpClient(port);
        }

        public void StartReceiving()
        {
            isReceiving = true;
            while (isReceiving)
            {
                try
                {
                    IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
                    byte[] receivedBytes = udpClient.Receive(ref endPoint);
                    string message = Encoding.UTF8.GetString(receivedBytes);
                    OnMessageReceived?.Invoke(this, message);
                }
                catch (Exception ex)
                {
                    // 处理接收异常
                    Debug.WriteLine($"UDP 接收错误: {ex.Message}");
                }
            }
        }

        public void StopReceiving()
        {
            isReceiving = false;
            udpClient.Close();
        }
        //--------------------------------
    }

}
