2021年1月16日星期六

Java Socket InputStream reads data but return in the wrong order

I developed an application using Java socket. I am exchanging messages with this application with the help of byte arrays. I have a message named M1, 1979 bytes long. My socket buffer length is 512 bytes. I read this message in 4 parts, each with 512 bytes, but the last one is of course 443 bytes. I will name these parts like A, B, C, and D. So ABCD is a valid message of mine respectively.

I have a loop with a thread which is like below.

BlockingQueue<Chunk> queue = new LinkedBlockingQueue<>();  InputStream in = socket.getInputStream()  byte[] buffer = new byte[512];    while(true) {    int readResult = in.read(buffer);    if(readResult != -1) {      byte[] arr = Arrays.copyOf(buffer, readResult);      Chunk c = new Chunk(arr);      queue.put(c);    }  }        

I'm filling the queue with the code above. When the message sending starts, I see the queue fill up in ABCD form but sometimes I put the data in the queue as a BACD. But I know that this is impossible because the TCP connection guarantees the order.

I looked at the dumps with Wireshark. This message comes correctly with a single tcp package. So there is no problem on the sender side. I am 100% sure that the message has arrived correctly but the read method does not seem to read in the correct order and this situation doesn't always happen. I could not find a valid reason for what caused this.

When I tried the same code on two different computers I noticed that the problem was in only one. The jdk versions on these computers are different. I looked at the version differences between the two jdk versions. When the Jdk version is "JDK 8u202", I am getting the situation where it works incorrectly. When I tried it with jdk 8u271, there was no problem. Maybe it is related to that but I wasn't sure. Because I have no valid evidence.

I am open to all kinds of ideas and suggestions. It's really on its way to being the most interesting problem I've ever encountered. Thank you for your help.

https://stackoverflow.com/questions/65754514/java-socket-inputstream-reads-data-but-return-in-the-wrong-order January 17, 2021 at 04:43AM

没有评论:

发表评论