UdpLoggerReceiver.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace MVMoniter
  10. {
  11. public class UdpLoggerReceiver
  12. {
  13. private UdpClient udpClient;
  14. private Thread receiveThread;
  15. public event Action<string> LogReceived;
  16. public UdpLoggerReceiver(int listenPort)
  17. {
  18. udpClient = new UdpClient(listenPort);
  19. receiveThread = new Thread(ReceiveLogs)
  20. {
  21. IsBackground = true
  22. };
  23. receiveThread.Start();
  24. }
  25. private void ReceiveLogs()
  26. {
  27. IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
  28. while (true)
  29. {
  30. try
  31. {
  32. byte[] data = udpClient.Receive(ref remoteEndPoint);
  33. string message = Encoding.UTF8.GetString(data);
  34. LogReceived?.Invoke(message); // 触发事件
  35. }
  36. catch (Exception ex)
  37. {
  38. Console.WriteLine($"日志接收失败: {ex.Message}");
  39. }
  40. }
  41. }
  42. public void Close()
  43. {
  44. udpClient?.Close();
  45. receiveThread?.Abort();
  46. }
  47. //-------------------------------------------------
  48. }
  49. }