1. Server-side
Packagecom.machuang.udp;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.SocketException; Public classSERVERUDP { Public Static voidMain (string[] args)throwsIOException {datagramsocket server=NewDatagramsocket (8888); byte[] container =New byte[1024]; Datagrampacket Packet=NewDatagrampacket (container, container.length); Server.receive (packet); byte[] Receivedata =Packet.getdata (); intLen =packet.getlength (); System.out.println (NewString (receivedata, 0, Len)); Server.close (); }}
2. Client
Packagecom.machuang.udp;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetSocketAddress;Importjava.net.SocketException; Public classCLIENTUDP { Public Static voidMain (string[] args)throwsIOException {datagramsocket client=NewDatagramsocket (6666); String msg= "Request Connection Server"; byte[] Msgbytes =msg.getbytes (); Datagrampacket Packet=NewDatagrampacket (Msgbytes, Msgbytes.length,NewInetsocketaddress ("localhost", 8888)); Client.send (packet); Client.close (); }}
Java establishes a UDP connection