Rev 215 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
import java.io.*;
import java.util.*;
import java.net.*;
import java.util.regex.*;
public class P2_Server
{
private static int portNumber = 1337;
private static int dropEvery = -1;
private static int sendCount = 1;
private static DatagramPacket packet;
private static DatagramSocket socket;
public static String readPacket (int maxlen)
{
byte[] buf = new byte[maxlen];
packet = new DatagramPacket (buf, buf.length);
try {
socket.receive (packet);
} catch (IOException e) {
System.out.println ("Caught exception in readPacket()");
e.printStackTrace();
return null;
}
System.out.println ("Recieved Packet. Len: " + packet.getLength());
String s = new String (buf, 0, packet.getLength() /*- 1*/);
System.out.println ("RcvdPacket: |" + s + "|");
return s;
}
public static boolean writePacket (String msg)
{
if (sendCount == dropEvery && !msg.equals("QUIT"))
{
System.out.println ("Dropped a packet");
sendCount = 0; // reset the sendCount
return true; // "Fake" send
}
else { sendCount++; }
System.out.println ("Num sent: " + sendCount);
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] buf = msg.getBytes();
packet = new DatagramPacket (buf, buf.length, address, port);
try {
socket.send (packet);
} catch (IOException e) {
System.out.println ("Caught exception in writePacket()");
e.printStackTrace();
return false;
}
return true;
}
public static int calcDrops (String s)
{
String dropRegex = "^DROP(\\d*)(.*)$";
Pattern p = Pattern.compile(dropRegex);
Matcher m = p.matcher(s);
if (m.matches())
return Integer.parseInt(m.group(1));
return -1;
}
public static void main (String[] args) throws Exception
{
boolean done = false;
socket = new DatagramSocket(portNumber);
packet = null;
String s;
// Try to get a "timeout info" packet
while (!done)
{
s = readPacket (8);
dropEvery = calcDrops(s);
if (dropEvery != -1)
{
done = true;
System.out.println ("dropEvery: " + dropEvery);
}
}
done = false;
// Keep reading until we get a quit packet
while (!done)
{
s = readPacket (5);
// Check and see if we got a quit message
if (s.equals("QUIT"))
{
done = true;
writePacket(s);
continue;
}
try {
s = P2_EncDec.convert4B (s);
} catch (IllegalArgumentException e) {
System.out.println ("Recieved a bad packet");
s = "BADVAL";
}
writePacket (s);
}
}
}