Importjava.net.*;/*sending text data over a UDP transmission 1. Setting up the Socket Service 2. Provide data and encapsulate it in a packet 3. Send data packets through the Sokect service delivery function 4. Close Resources*/classudpsend{ Public Static voidMain (string[] arg)throwsException {//1. Create a UDP service. by Datagramsocket ObjectDatagramsocket ds =NewDatagramsocket (1234); //2. Identify the data and encapsulate it as a packet byte[] buf = "UDP is Coming". GetBytes (); Datagrampacket DP=NewDatagrampacket (Buf,buf.length,inetaddress.getbyname ("127.0.0.1"), 4567); //3. Send the existing data packets through the socket serviceDs.send (DP); //4. Close ResourcesDs.close (); } }/*Requirements: Define an application to be willing to receive UDP protocol transmission data ideas: 1. Define a Udpsocket service, typically listening on a port 2. Define a packet. Because you want to store the received byte data because there are more features in the packet object that can extract different data information from the byte Data 3. The received data is stored in a defined packet by the socket service's Receive method 4. With the unique functionality of the packet object, these different data are taken out and printed on the console 5. Close Resources */classudprece{ Public Static voidMain (string[] args)throwsexception{//1. Create UDP, set up endpointDatagramsocket ds=NewDatagramsocket (4567); //2. Define the packet to store byte[] buf=New byte[1024]; Datagrampacket DP=NewDatagrampacket (buf,buf.length); //3. Data that is received indirectly through the receive method is stored in the packetDs.receive (DP); //4. Get the data from the data packet methodString ip=dp.getaddress (). gethostaddress (); String Data=NewString (Dp.getdata (), 0, Dp.getlength ()); intport=Dp.getport (); SYSTEM.OUT.PRINTLN (IP+ ":" +port+ "------" +data); //5. Close ResourcesDs.close (); } }
Java UDP network programming