1 Importjava.net.*;2 ImportJava.io.*;3 classUdpsdemo4 {5 Public Static voidMain (String[]args)throwsException6 {7 //Create a send-side socket service8Datagramsocket ds=NewDatagramsocket ();9 //ready to send packetsTenBufferedReader br=NewBufferedReader (NewInputStreamReader (system.in)); One String Line; A while((Line=br.readline ())! =NULL) - { - if("886". Equals (line)) the Break; - byte[] buf=line.getbytes (); - //Data Package -Datagrampacket dp=NewDatagrampacket (Buf,buf.length,inetaddress.getbyname ("localhost"), 10000); + //Send - Ds.send (DP); + } A ds.close (); at } - } - - classUdprdemo - { - Public Static voidMain (String[]args)throwsException in { - //create a receive-side socket service that explicitly listens for port numbers toDatagramsocket ds=NewDatagramsocket (10000); + while(true) - { the //preparing packets to receive data * byte[] buf=New byte[1024]; $Datagrampacket dp=NewDatagrampacket (buf,buf.length);Panax Notoginseng //Receive - Ds.receive (DP); theString address=dp.getaddress (). gethostaddress (); +String Data=NewString (Dp.getdata (), 0, Dp.getlength ()); ASystem.out.println ("IP:" +address); theSystem.out.println ("Data:" +data); + } - } $}
View Code
UDP Learning 3 (send data via keyboard input demo)