The function of the example is to implement the system time of the client program to the server side, and after the server receives the time, the feedback string "OK" to the client. The client code that implements this feature looks like this:
package UDP;
Import java.net.*
Import java.util.*
/**
* Simple UDP client, implement system time function to server side
*/
public class Simpleudpclient {
public static void Main (string[] args) {
Datagramsocket ds = null; The Connection object
Datagrampacket SENDDP;//Send Packet object
Datagrampacket RECEIVEDP;//Receive Packet object
String serverhost = "127.0.0 .1 "; server IP
int serverport = 10010; The server port number
try{
//establishes the connection
ds = new Datagramsocket ();
Initialize send data
Date d = new Date ();//Current time
String content = D.tostring ();//Convert to String
byte[] data = CONTENT.G Etbytes ();
//Initialize Send package object
InetAddress address = Inetaddress.getbyname (serverhost);
SENDDP = new Datagrampacket (data,data.length,address,serverport);
//Send
Ds.send (SENDDP);
//initialization receive data
Byte[] b = new byte[1024];
RECEIVEDP = new Datagrampacket (b,b.length);
//Receive
Ds.receive (RECEIVEDP);
Reads the feedback content and outputs the
byte[] response = RECEIVEDP.GEtdata ();
int len = Receivedp.getlength ();
String s = new string (Response,0,len);
System.out.println ("Server-side feedback is:" + s);
}catch (Exception e) {
E.printstacktrace ();
}finally{
try{
//close connection
Ds.close ();
}catch (Exception e) {}
}
}
}