Rev 211 | Rev 213 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
import java.io.*;
import java.net.*;
import java.util.*;
public class P2_Client
{
private static int soTimeout = 3000; // 3000 ms timeout = 3 sec
private static DatagramSocket socket;
private static DatagramPacket packet;
private static int portNumber = 1337;
public static String readPacket (int maxlen)
{
byte[] buf = new byte[maxlen];
packet = new DatagramPacket (buf, buf.length);
try {
socket.receive (packet);
} catch (SocketTimeoutException e) {
System.out.println ("Read timed out, requesting retransmit");
return null;
} catch (PortUnreachableException e) {
System.out.println ("Caught PortUnreachableException, are you" +
" sure the server is running?");
System.exit(1);
} catch (IOException e) {
System.out.println ("Caught exception in readPacket()");
e.printStackTrace();
return null;
}
return new String (buf, 0, packet.getLength()/*- 1*/);
}
public static boolean writePacket (String msg) throws Exception
{
InetAddress address = InetAddress.getLocalHost();
int port = portNumber;
byte[] buf = msg.getBytes();
packet = new DatagramPacket (buf, buf.length, address, port);
try {
socket.send (packet);
} catch (PortUnreachableException e) {
System.out.println ("Caught PortUnreachableException, are " +
"you sure the server is running?");
System.exit(1);
} catch (IOException e) {
System.out.println ("Caught exception in writePacket()");
e.printStackTrace();
return false;
}
return true;
}
public static void main (String[] args) throws Exception
{
int dropHowMany = 0;
socket = new DatagramSocket();
socket.connect (InetAddress.getLocalHost(), portNumber);
socket.setSoTimeout (soTimeout);
BufferedReader kbd = new BufferedReader (
new InputStreamReader (
System.in));
try {
dropHowMany = Integer.parseInt(args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println ("You need to call the program with \'java P2_Client <num>\'");
System.exit(1);
}
writePacket ("DROP" + dropHowMany);
System.out.print ("% decode: ");
String msg = kbd.readLine();
String reply;
boolean done = false;
while (!done)
{
writePacket (msg);
reply = readPacket(5);
while (reply == null)
{
System.out.println ("Packet lost, retransmitting...");
writePacket (msg);
reply = readPacket(5);
}
if (reply.equals("QUIT"))
{
done = true;
continue;
}
System.out.println ("-> reply: " + reply);
System.out.print ("% decode: ");
msg = kbd.readLine();
}
}
}