Client
Package org.udp;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
public class UdpClient {
public static void Main (string[] args) throws exception{
Datagramsocket ds = null;
byte[] buf = new byte[2014];
Datagrampacket DP = NULL;
ds = new Datagramsocket (9000);
DP = new Datagrampacket (buf,1024);
System.out.println ("Waiting to receive data. ");
Ds.receive (DP);
String str = new String (Dp.getdata (), 0,dp.getlength ()) + "from"
+dp.getaddress (). Gethostaddress () + ":" +dp.getport ();
System.out.println (str);
Ds.close ();
}
}
Program Run Result: wait to receive data.
Server-side
Package org.udp;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
public class Udpserver {
public static void Main (string[] args) throws exception{
Datagramsocket ds = null;
Datagrampacket DP = NULL;
ds = new Datagramsocket (3000);
String str = "Hello word";
DP = new Datagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 9000);
SYSTEM.OUT.PRINTLN ("Send message. ");
Ds.send (DP);
Ds.close ();
}
}
Program Run Result: send message.
The client can accept the information sent from the server side, the client program running result: waiting to receive data.
Hello wordfrom127.0.0.1:3000