using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Timers;
namespace HeartbeatSender{
    public class heartbeatSender
    {
        private readonly UdpClient udpClient;
        private readonly IPEndPoint remoteEndPoint;
        private readonly System.Timers.Timer heartbeatTimer;
        public IPEndPoint RemoteEndPoint => remoteEndPoint;
        public heartbeatSender(string targetIp, int targetPort, int intervalMilliseconds = 3000)
        {
            udpClient = new UdpClient();
            // 設置 IP 和 PORT
            remoteEndPoint = new IPEndPoint(IPAddress.Parse(targetIp), targetPort);
            // 每3秒發送一次
            heartbeatTimer = new System.Timers.Timer(intervalMilliseconds);
            heartbeatTimer.Elapsed += SendHeartbeat;
            heartbeatTimer.AutoReset = true;
        }
        private void SendHeartbeat(object sender, ElapsedEventArgs e)
        {
            try
            {
                string heartbeatMessage = "HEARTBEAT";
                byte[] data = Encoding.UTF8.GetBytes(heartbeatMessage);
                udpClient.Send(data, data.Length, remoteEndPoint);
                Console.WriteLine($"Heartbeat sent to {remoteEndPoint.Address}:{remoteEndPoint.Port}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending heartbeat: {ex.Message}");
            }
        }
        public void Start() => heartbeatTimer.Start();
        public void Stop() => heartbeatTimer.Stop();
    }
}