packet.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // common packet class used by both SENDER and RECEIVER
  2. import java.nio.ByteBuffer;
  3. public class packet {
  4. // constants
  5. private final int maxDataLength = 500;
  6. private final int SeqNumModulo = 32;
  7. // data members
  8. private int type;
  9. private int seqnum;
  10. private String data;
  11. //////////////////////// CONSTRUCTORS //////////////////////////////////////////
  12. // hidden constructor to prevent creation of invalid packets
  13. private packet(int Type, int SeqNum, String strData) throws Exception {
  14. // if data seqment larger than allowed, then throw exception
  15. if (strData.length() > maxDataLength)
  16. throw new Exception("data too large (max 500 chars)");
  17. type = Type;
  18. seqnum = SeqNum % SeqNumModulo;
  19. data = strData;
  20. }
  21. // special packet constructors to be used in place of hidden constructor
  22. public static packet createACK(int SeqNum) throws Exception {
  23. return new packet(0, SeqNum, new String());
  24. }
  25. public static packet createPacket(int SeqNum, String data) throws Exception {
  26. return new packet(1, SeqNum, data);
  27. }
  28. public static packet createEOT(int SeqNum) throws Exception {
  29. return new packet(2, SeqNum, new String());
  30. }
  31. ///////////////////////// PACKET DATA //////////////////////////////////////////
  32. public int getType() {
  33. return type;
  34. }
  35. public int getSeqNum() {
  36. return seqnum;
  37. }
  38. public int getLength() {
  39. return data.length();
  40. }
  41. public byte[] getData() {
  42. return data.getBytes();
  43. }
  44. //////////////////////////// UDP HELPERS ///////////////////////////////////////
  45. public byte[] getUDPdata() {
  46. ByteBuffer buffer = ByteBuffer.allocate(512);
  47. buffer.putInt(type);
  48. buffer.putInt(seqnum);
  49. buffer.putInt(data.length());
  50. buffer.put(data.getBytes(),0,data.length());
  51. return buffer.array();
  52. }
  53. public static packet parseUDPdata(byte[] UDPdata) throws Exception {
  54. ByteBuffer buffer = ByteBuffer.wrap(UDPdata);
  55. int type = buffer.getInt();
  56. int seqnum = buffer.getInt();
  57. int length = buffer.getInt();
  58. byte data[] = new byte[length];
  59. buffer.get(data, 0, length);
  60. return new packet(type, seqnum, new String(data));
  61. }
  62. }