Receiver: 1, establish the Udpsocket service, set the port to the receiver; 2. Define an empty packet to store the received byte data, and use the packet object to easily extract the different data information in the byte data; 3. The received data is stored in a defined packet through the Receive method of the socket service, and the data is removed by the unique functions of the packet object, printed on the console; 5. Close the resource.
classudprecevie{ Public Static voidMain (string[] args)throwsException {datagramsocket ds=NewDatagramsocket (10000); while(true) { byte[] buf =New byte[1024]; Datagrampacket DP=NewDatagrampacket (But, but.length); Ds.receive (DP);//blocking method, no data, etc.String IP =dp.getaddress (). gethostadress (); String Data=NewString (Dp.getdata (), 0, Dp.getlength ()); intPort =Dp.getport (); } ds.close (); }}
Send receive with Datagramsocket, receive (Datagrampacket p), send (Datagrampacket p), Datagrampacket for encapsulating data. Send end: 1, establish Udpsocket service, 2, provide data, and encapsulate data into packet, 3, send data packets by socket service, 4, close resource.
class udpsend{ publicstaticvoidthrows Exception { New Datagramsocket (); byte [] data = "UDP come in". GetBytes (); New Datagrampacket (data, Data.length, Inetaddresss.getbyname ("192.168.1.255"), +); Ds.send (DP); Ds.close (); }}
UDP Simple Example