using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System; using System.Net; using System.Net.Sockets; namespace EasyTemplate.Service.Common { public class UdpServer { private UdpClient udpClient; private Thread listenThread; private const int ListenPort = 10000; // 监听端口号 string data = string.Empty; public UdpServer() { udpClient = new UdpClient(ListenPort); listenThread = new Thread(new ThreadStart(ListenForClients)); listenThread.IsBackground = true; // 设置为后台线程,当主程序结束时自动结束 listenThread.Start(); } private void ListenForClients() { try { while (true) // 无限循环监听客户端消息 { Console.WriteLine("Waiting for broadcast"); IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, ListenPort); byte[] bytes = udpClient.Receive(ref anyIP); // 接收数据 data = Encoding.UTF8.GetString(bytes); Console.WriteLine($"Received broadcast from {anyIP} :"); Console.WriteLine($" {Encoding.UTF8.GetString(bytes, 0, bytes.Length)}"); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } public void StopServer() { udpClient.Close(); // 关闭UdpClient以停止监听 } } }