async Task ListenForUdp(int port, Action<UdpReceiveResult> receivedHandle) { using (var udpClient = new UdpClient(port)) { while (true) { try { receivedHandle(await udpClient.ReceiveAsync()); } catch (Exception ex) { // 处理异常 } } } }
var port = 61110; Console.WriteLine($"开始监听[{port}]端口"); // 执行监听 ListenForUdp(port, result => { // 收到消息后打印在控制台 Console.WriteLine($"[{DateTime.Now.ToLongTimeString()}] {result.RemoteEndPoint} => {Encoding.UTF8.GetString(result.Buffer)}"); }); // 任意键结束 Console.ReadKey();
使用Socket测试工具,能正常接收到数据。