this.cin = new DataInputStream(this.csocket.getInputStream()); public class ReceiveMessage extends Thread{ public void run(){ while(stop == false) try { if(cin.available()>0) receMessage(); } catch (IOException e) { e.printStackTrace(); } } } // choke, unchoke, interested, notinterested, have, bitfield, request, piece public void receMessage(){ int rv=0; byte[] length = new byte[4]; // total length try { rv = cin.read(length, 0, 4); } catch (IOException e) { e.printStackTrace(); } if(rv <=0) return; byte[] type = new byte[1]; try { cin.read(type, 0, 1); } catch (IOException e) { e.printStackTrace(); } int size = byte2int(length) -4 -1; //size of payload clearPayload(); if(size > 0){ try { cin.read(this.payload, 0, size); } catch (IOException e) { e.printStackTrace(); } } byte mtype = type[0]; switch(mtype){ case (byte)0: receNoPayload((byte)0); break; case 1: receNoPayload((byte)1); break; case 2: receNoPayload((byte)2); break; case 3: receNoPayload((byte)3); break; case 4: receHave(payload); break; case 5: receBitField(payload); break; case 6: receRequest(payload); break; case 7: recePiece(payload, size); break; default: System.out.println("wrong message type!"); } } the code above is used to read data from socket. I create a thread to read data from socket.and then analyze the data according the type of message contained in data. Now, the problem is if I transfer 100 bytes into socket, I can do everything correctly; however, if I transfer 1000 bytes into socket, sometimes, the data read out is wrong. for example, the variable type cannot be greater than 7 normally. But now the type read out is greater than 7, which is wrong.
in both case, I do not change anything, except the size of data transferred.
please help me, thank you! I have done everything I can do, but i still cannot figure it out.