// 定义套接字 //private Socket receiveSocket; //private Socket sendSocket; public AsyncUdpClient() { // 本机节点 localEP = new IPEndPoint(IPAddress.Any, listenPort); // 远程节点 remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort); // 实例化 udpReceive = new UdpClient(localEP); udpSend = new UdpClient(); // 分别实例化udpSendState、udpReceiveState udpSendState = new UdpState { ipEndPoint = remoteEP, udpClient = udpSend }; udpReceiveState = new UdpState { ipEndPoint = remoteEP, udpClient = udpReceive }; //receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //receiveSocket.Bind(localEP); //sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //sendSocket.Bind(remoteEP); }
// 接收回调函数 public void ReceiveCallback(IAsyncResult iar) { UdpState udpState = iar.AsyncState as UdpState; if (iar.IsCompleted) { Byte[] receiveBytes = udpState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint); string receiveString = Encoding.Unicode.GetString(receiveBytes); Console.WriteLine("Received: {0}", receiveString); receiveDone.Set(); } }
// 发送回调函数 public void SendCallback(IAsyncResult iar) { UdpState udpState = iar.AsyncState as UdpState; if (iar.IsCompleted) { Console.WriteLine("第{0}个发送完毕!", udpState.counter); Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar)); //if (udpState.counter == 10) //{ // udpState.udpClient.Close(); //} sendDone.Set(); } }