UdpServer.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. namespace EasyTemplate.Service.Common
  10. {
  11. public class UdpServer
  12. {
  13. private UdpClient udpClient;
  14. private Thread listenThread;
  15. private const int ListenPort = 10000; // 监听端口号
  16. string data = string.Empty;
  17. public UdpServer()
  18. {
  19. udpClient = new UdpClient(ListenPort);
  20. listenThread = new Thread(new ThreadStart(ListenForClients));
  21. listenThread.IsBackground = true; // 设置为后台线程,当主程序结束时自动结束
  22. listenThread.Start();
  23. }
  24. private void ListenForClients()
  25. {
  26. try
  27. {
  28. while (true) // 无限循环监听客户端消息
  29. {
  30. Console.WriteLine("Waiting for broadcast");
  31. IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, ListenPort);
  32. byte[] bytes = udpClient.Receive(ref anyIP); // 接收数据
  33. data = Encoding.UTF8.GetString(bytes);
  34. Console.WriteLine($"Received broadcast from {anyIP} :");
  35. Console.WriteLine($" {Encoding.UTF8.GetString(bytes, 0, bytes.Length)}");
  36. }
  37. }
  38. catch (Exception e)
  39. {
  40. Console.WriteLine(e.ToString());
  41. }
  42. }
  43. public void StopServer()
  44. {
  45. udpClient.Close(); // 关闭UdpClient以停止监听
  46. }
  47. }
  48. }