Send (sender ):
Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import java.net. datagrampacket; import java.net. datagramsocket; import java.net. inetaddress; import java.net. socketexception; public class senddemo1 {Private Static final int Port = 8080; Private Static final string IP = "localhost"; public static void main (string [] ARGs) {sendhandler ();} private Static void sendhand Ler () {datagramsocket sendsocket = NULL; try {While (true) {// create a socket sendsocket = new datagramsocket (); // enter bufferedreader BR = new bufferedreader (New inputstreamreader (system. in); string send = BR. readline (); byte [] Buf = Send. getbytes (); // sets the packet content, length, and address to which the packet is sent and the port datagrampacket dp = new datagrampacket (BUF, Buf. length, inetaddress. getbyname (IP), Port); // send the data packet sendsocket. send (DP) ;}} catch (socketexception E) {E. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} finally {If (sendsocket! = NULL) {sendsocket. Close ();}}}}
Receive (receiver ):
Import Java. io. ioexception; import java.net. datagrampacket; import java.net. datagramsocket; import java.net. socketexception; public class receiverdemo1 {Private Static final int Port = 8080; public static void main (string [] ARGs) {receivehandler ();} Private Static void receivehandler () {datagramsocket receivesocket = NULL; try {// listen to receivesocket = new datagramsocket (port) on port 8080; // while loop, waiting for receiving data while (T Rue) {// create a package and receive data byte [] Buf = new byte [1024]; datagrampacket dp = new datagrampacket (BUF, Buf. length); receivesocket. receive (DP); // get the IP address and the data content in the package string IP = DP. getaddress (). gethostaddress (); string data = new string (DP. getdata (), 0, DP. getlength (); system. out. println (IP + ":" + Data) ;}} catch (socketexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} finally {If (receivesoc Ket! = NULL) {receivesocket. Close ();}}}}
Start the receiver first, and then start the sender