PackageCn.com.pb.ask;Importjava.io.IOException;Importjava.net.*; Public classReceive { Public Static voidMain (string[] args) {Datagrampacket DP=NULL; Datagramsocket DS=NULL; Datagrampacket Dpto=NULL; Try{ //Create a Datagrampacket object to prepare to receive packets byte[] buf=New byte[1024]; DP=NewDatagrampacket (buf,buf.length); //Create a Datagramsocket object to receive datads=NewDatagramsocket (8800); Ds.receive (DP); //Display the information receivedString mess=NewString (Dp.getdata (), 0, Dp.getlength ()); System.out.println (Dp.getaddress (). Gethostaddress ()+ "SAY:" +mess); String reply= "Hello, I am in, please consult!" "; //Show with local dialog boxSYSTEM.OUT.PRINTLN ("I said:" +reply); //creating Datagrampacket objects, encapsulating dataSocketAddress sa=dp.getsocketaddress (); Dpto=NewDatagrampacket (Reply.getbytes (), reply.getbytes (). length, SA); Ds.send (Dpto); }Catch(IOException e) {e.printstacktrace (); }finally{ds.close (); } }}
PackageCn.com.pb.ask;Importjava.io.IOException;Importjava.net.*; Public classSend { Public Static voidMain (string[] args) {inetaddress ia=NULL; Datagramsocket DS=NULL; Try{String mess= "Hello, I'd like to ask a question." "; //Show with local dialog boxSYSTEM.OUT.PRINTLN ("I said:" +mess); //get Local Host addressIa=inetaddress.getbyname ("localhost"); //creating Datagrampacket objects, encapsulating dataDatagrampacket dp=NewDatagrampacket (Mess.getbytes (), mess.getbytes (). Length, ia,8800); //Create a Datagramsocket object to send data to the serverds=NewDatagramsocket (); Ds.send (DP); byte[] buf=New byte[1024]; Datagrampacket Dpre=NewDatagrampacket (buf,buf.length); //Create a Datagramsocket object to receive data//ds=new Datagramsocket (8800);ds.receive (Dpre); //Display the information receivedString reply=NewString (Dpre.getdata (), 0, Dpre.getlength ()); System.out.println (Dpre.getaddress (). Gethostaddress ()+ "SAY:" +reply); }Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{ //Close the Datagramsocket objectDs.close (); } }}
45. Customer Consultation Questions