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 port = 7;
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 e) {
System.err.println(e);
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, port);
ds.send(dp);
Thread.yield();
}
}
catch (IOException e) {
System.err.println(e);
}
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(bufffer.length);
ds.receive(incoming);
byte[] data = incoming.getData();
System.out.println(new String(data, 0, incoming.getLength()));
}
catch (IOException e) {
System.err.println(e);
}
}
}
}