Implemented by the Datagramsocket class. This class represents the socket used to send and receive datagram packets.
The send-side code is as follows:
2 3 Importjava.io.IOException;4 Importjava.net.*;5 ImportJava.util.Scanner;6 7 Public classSendImplementsrunnable{8 @Override9 Public voidrun () {Ten //Create a socket that sends a message OneDatagramsocket Sendsocket =NULL; A Try { -Sendsocket =NewDatagramsocket (); -}Catch(SocketException e) { the e.printstacktrace (); - } - while(true) { - Try { +SYSTEM.OUT.PRINTLN ("Send-side Send Message"); -Scanner sc =NewScanner (system.in); +String msg =Sc.next (); A at byte[] bytes = Msg.getbytes ();//the sent content is converted into a byte array -inetaddress IP = inetaddress.getbyname ("192.168.31.169");//IP address of accepted content - - //Create a packet to send, and then send it with a socket -Datagrampacket Datagrampacket =NewDatagrampacket (bytes,bytes.length,ip,8080); - //send a packet with a socket in sendsocket.send (datagrampacket); - to}Catch(SocketException e) { + e.printstacktrace (); -}Catch(unknownhostexception e) { the e.printstacktrace (); *}Catch(IOException e) { $ e.printstacktrace ();Panax Notoginseng } - } the } + A Public Static voidMain (string[] args) { theSend s =NewSend (); +Thread thread =NewThread (s); - Thread.Start (); $ } $}
The receive-side code is as follows:
2 3 Importjava.io.IOException;4 ImportJava.net.DatagramPacket;5 ImportJava.net.DatagramSocket;6 Importjava.net.InetAddress;7 Importjava.net.SocketException;8 9 Public classReceiveImplementsRunnable {Ten @Override One Public voidrun () { ASystem.out.println ("Receive Side"); - //Create a socket that accepts messages -Datagramsocket Recevicesocket =NULL; the Try { -Recevicesocket =NewDatagramsocket (8080); -}Catch(SocketException e) { - e.printstacktrace (); + } - while(true) { + Try { A byte[] bytes =New byte[2048]; at //Create a packet to accept the message -Datagrampacket Datagrampacket =NewDatagrampacket (bytes,bytes.length); - //accepting packets with sockets - recevicesocket.receive (datagrampacket); - //get the IP address of the sending end -inetaddress IP =datagrampacket.getaddress (); in //converts the received message to a string -String rec =NewString (Datagrampacket.getdata ()); toSystem.out.println (ip.gethostaddress () + "message Sent:" +rec); + -}Catch(SocketException e) { the e.printstacktrace (); *}Catch(IOException e) { $ e.printstacktrace ();Panax Notoginseng } - } the } + A Public Static voidMain (string[] args) { theReceive r =NewReceive (); +Thread thread =NewThread (r); - Thread.Start (); $ } $}
The while loop is used because the message is always received and sent.
Note: The port on the sending side is consistent with the port on the receiving side.
Here I accept that the IP address of the message is set to its own IP address to demonstrate the actual effect.
Use UDP in Java to implement simple chat functions