ByteArrayInputStream question

Greetings everyone,

I'm working on a project to do a simple .txt file transfer over a UDP protocol. However we have to make it more reliable by calculating checksum's and sequence numbers and send ack's via the stop and wait protocol (rdt 2.2). So here's my question:

In my receiever class I have this:

publicbyte[] rdt_receive(){

byte[] data =newbyte[maxPacketSize];

try{

DatagramPacket recievedPacket =new DatagramPacket(data,

data.length);

// data recieving part

clientSocket.receive(recievedPacket);

ByteArrayInputStream bais =new ByteArrayInputStream(recievedPacket.getData());

DataInputStream dis =new DataInputStream(bais);

int seqNum = dis.read();

System.out.println(seqNum);

short checkSum = dis.readShort();

System.out.println(checkSum);

/*

System.out.println("Sequence Number of packet received: " + seqNum);

System.out.println("Sequence Number Expected: " + expectedSeqNum);

if(seqNum != expectedSeqNum){

System.err.println("Woops...wrong sequence number");

}*/

int i = 0;

byte newest = dis.readByte();

while(Byte.valueOf(newest) !=null){

data[i] = newest;

newest = dis.readByte();

i++;

}

for(int j=0; j<data.length; j++){

System.out.print(data[i] +" ");

}

//short ourCheckSum = getCheckSum(data);

//System.out.println("CheckSum of packet received: " + checkSum);

//System.out.println("CheckSum we calculated " + ourCheckSum);

expectedSeqNum++;

}catch (Exception e){

System.err.println(e.getMessage() +" receive method");

}

return data;

}

However when I read from the bais, I watch the position while debugging and my i in the while loop increases slower than the bais position counter. I have already figured out that it goes like this:

dis.readInt() increases the position counter by 1

dis.readShort() increases the position counter by 2

The checksum is calculated as a 16 bit short so naturally that's 2 bytes so I guess the +2 on the counter is acceptable, but I can't figure out how to get this receive method to work. If anyone can give me any advice/needs me to post more code, just let me know.

Oh p.s. the error I'm getting is Null (because the position counter goes higher than the InputStream)

Thanks,

Alex

Message was edited by:

thequietone>

[3585 byte] By [thequietonea] at [2007-11-26 22:02:37]
# 1

Two things jump out at me. First:

> dis.readInt() increases the position counter by 1

You aren't using readInt(). You're calling read(), a method inherited from FilterInputStream that reads one byte and returns it as an int with a value from 0 to 255, which is probably not what you want. If you did call readInt(), it would advance the position counter by four.

Second: Byte.valueOf(newest) != null

will always evaluate to true.

Also, I don't know if I'm guessing your intention correctly, but data.length will always be equal to maxPacketLength, no matter how many bytes are actually read.

uncle_alicea at 2007-7-10 10:43:15 > top of Java-index,Java Essentials,Java Programming...