Udpsend.java
Import java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
Import java.net.SocketException;
Import java.net.UnknownHostException;
PublicClass Udpsend {
PublicStaticvoid Main (String args[]) {
Datagramsocket ds =Null
Datagrampacket DP =null;
try{
ds = new datagramsocket (+); // Instantiate a UDP socket and bind 3000 bindings
}catch (SocketException e) {
}
String str = "Hello world";
try{
DP = new Datagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 9000);
}
catch (Unknownhostexception ex1) {
}
Ds.send (DP); // }< Span style= "color: #0000ff;" >catch (IOException e) {
}
Ds.close ();
}
}
Udpreceive.javaImport java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
PublicClass Udpreceive {
PublicStaticvoid Main (String args[]) {
Datagramsocket ds =Null//Create a Socket object
byte[] buf =NewBYTE[1024];//Instantiate an array
Datagrampacket DP =Null//Create a socket structure object
try{
DS =New Datagramsocket (9000);//Instantiating and binding ports
}
catch (IOException e) {
}
DP =New Datagrampacket (buf,1024);
try{
Ds.receive (DP);// receive data and store in DP
}
catch (IOException E2) {
}
String str = new String (Dp.getdata (), 0,dp.getlength ()) + "from" +dp.getaddress (). Gethostaddress () + ":" +dp.getport ( );
System.out.println (str); // print received content
Ds.close ();
}
}
Java Socket routine 3 UDP