Java UDP network programming is implemented mainly through the Datagramsocket and Datagrampacket two classes, the following is an example program,
The server listens on UDP 2000 ports and prints the received long type values
The client then gets a long value by entering it and sends it to the server
Server:/**//* Coding by NYZHL *
Import java.net. * ;
Import java.io. * ;
public class Datagramserver ... {
public static void Main (string[] args) ... {
Datagramsocket ds = null;
Try ... {
ds = new Datagramsocket (2000);
}
catch (SocketException e) ... {
E.printstacktrace ();
System.exit (-1);
}
byte[] buffer = new byte[1024];
Datagrampacket DP = new Datagrampacket (buffer,buffer.length);
while (true) ... {
DataInputStream in = new DataInputStream (
New Bytearrayinputstream (buffer)
);
Try ... {
Ds.receive (DP);
System.out.println (In.readlong ());
In.close ();
}
catch (IOException e) ... {
E.printstacktrace ();
Continue
}
}
Ds.close (); JDK prompts "statements that cannot be accessed"
Because the front is a dead loop, you can't execute the following statement anyway
}
}
Client:/**//* Coding by NYZHL *
Import java.net. * ;
Import java.io. * ;
public class datagramclient ... {
public static void Main (string[] args) ... {
Datagramsocket ds = null;
Try ... {
ds = new Datagramsocket ();
}
catch (SocketException e) ... {
E.printstacktrace ();
System.exit (-1);
}
BufferedReader typereader = new BufferedReader (
New InputStreamReader (system.in)
);
Long data = 0;
while (true) ... {
Bytearrayoutputstream bytesout = new Bytearrayoutputstream ();
DataOutputStream dataout = new DataOutputStream (bytesout);
Try ... {
Data =<