In my program, pc sends data to my android phone continuously. Each time pc send 62 bytes(24 for head and 38 for content). My program runs well. But sometimes my phone can read 24 bytes for head and only 10 bytes for content.
I receive data via a non-block socketchannel.
private SocketChannel client = null;
public int read(byte[] data,int offset, int len){
try {
ByteBuffer buffer = ByteBuffer.allocate(len);
int read_len = client.read(buffer);
if(read_len == 0){
}else if(read_len == -1){
}else{
buffer.flip();
buffer.get(data, offset, read_len);
}
return read_len;
} catch (IOException e) {
e.printStackTrace();
}
return -2;
}
How can I solve this problem?
It’s possible there is a network problem, but I think it’s more likely that since TCP is a stream oriented protocol, which does not preserve message boundaries, you are occasionally getting payloads that do not correspond with the bytes sent by the pc. This is OK and expected. It just means you have to do a bit more work.
I assume that with your
readmessage you want to keep reading data until you have enough data to fill the supplied byte array. Try something this:The nice thing about reading into a byte buffer is that it takes care of concatenating the bytes correctly on multiple reads, so just loop until full.
BTW – don’t forget to subtract the offset (in case it is non-zero) from the length of your buffer.