C#UDP编程总结
// 如果只使用一个EndPoint,维持一个引用。 private static UdpClient udpClient; static void Main(string[] args) { if (udpClient != null) { // 这段很重要 udpClient.Close(); } udpClient = new UdpClient(10250); udpClient.Client.SendBufferSize = 120400; udpClient.Client.SendTimeout = 1000; udpClient.Client.ReceiveBufferSize = 120400; udpClient.Client.ReceiveTimeout = 1000; IPEndPoint endPoint; try { endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1025); udpClient.Connect(endPoint); } catch (Exception) { return; // 连不上目标端口 } var bytes = new byte[0]; udpClient.Send(bytes, bytes.Length); var receiver = new BackgroundWorker(); receiver.WorkerSupportsCancellation = true; receiver.DoWork += delegate { while (receiver.CancellationPending) { try { var a = udpClient.Receive(ref endPoint); receiver.CancelAsync(); } catch (Exception) { return; // 对方断开连接或超时 } } }; receiver.RunWorkerAsync(); }