Most of the time a program needs to both receive and send UDP datagrams. For example, the UDP echo service listens on port 7. When it receives a datagram it copies the data out of the datagram into a new datagram and sends it back to the sending host. (Why can't it just resend the same datagram?)
The following UDPEchoClient
reads what the user types
on System.in
and sends it to an echo server specified
on the commond line. Note that precisely because UDP is unreliable,
you're not guaranteed that each line you type will in fact be
echoed back. It may be lost going between client and server or
returning from server to client.
import java.net.*;
import java.io.*;
public class UDPEchoClient extends Thread {
public final static int DEFAULT_PORT = 7;
private DatagramSocket ds;
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String theLine;
DatagramSocket ds = null;
InetAddress server = null;
try {
server = InetAddress.getByName("metalab.unc.edu");
ds = new DatagramSocket();
}
catch (IOException ex) {
System.err.println(ex);
System.exit(1);
}
UDPEchoClient uec = new UDPEchoClient(ds);
uec.start();
try {
while ((theLine = br.readLine()) != null) {
byte[] data = theLine.getBytes();
DatagramPacket dp = new DatagramPacket(data, data.length,
server, DEFAULT_PORT);
ds.send(dp);
Thread.yield();
}
}
catch (IOException ex) {
System.err.println(ex);
}
uec.stop();
}
public UDPEchoClient(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
byte[] buffer = new byte[1024];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
while (true) {
try {
incoming.setLength(buffer.length);
ds.receive(incoming);
byte[] data = incoming.getData();
System.out.println(new String(data, 0, incoming.getLength()));
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}