//初始化 private void myUdp() { Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //IP address of the server machine IPAddress ipAddress = IPAddress.Loopback;//.Parse(txtServerIP.Text); //Server is listening on port 1000 IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 6002); epServer = (EndPoint)ipEndPoint; //本UDP绑定端口,不用动态端口,用于接收返回 IPEndPoint myEndPoint = new IPEndPoint(ipAddress, 6005); clientSocket.Bind((EndPoint)myEndPoint); //Start listening to the data asynchronously clientSocket.Connect(epServer); clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null); } //接收 private void OnReceive(IAsyncResult ar) { try { clientSocket.EndReceive(ar); //Convert the bytes received into an object of type Data string msgReceived = GetString(byteData); clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null); } catch (ObjectDisposedException) { } } //发送 public void SendData() { byte[] btData = GetBytes(msgToSend); //Send it to the server clientSocket.BeginSendTo(btData, 0, btData.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null); } private void OnSend(IAsyncResult ar) { try { if (clientSocket != null) { clientSocket.EndSend(ar); } } catch (ObjectDisposedException) { } }