public ByteBuffer encode() { int length = 2; for (Packet packet : content) { int pLength = packet.encode().array().length; if (pLength >= 255) { length += 3; } else { length += 1; } length += pLength; } ByteBuffer data = ByteBuffer.allocate(length); data.order(ByteOrder.BIG_ENDIAN).putShort((short) 3); for (Packet packet : content) { byte[] pData = packet.encode().array(); if (pData.length >= 255) { data.put((byte) 255); addShort(data, (short) pData.length); } else { data.put((byte) pData.length); } data.put(pData); } return data; }
private int getPacketLength(Packet packet) { if (packet instanceof DataChannelA) return ((DataChannelA) packet).getLength(); else if (packet instanceof Acknowledge || packet instanceof OutOfOrder) return 4; else if (packet instanceof Disconnect) return 8; return packet.encode().array().length; }