Java serial communication: how to discard unwanted data correctly.

is using RXTX to write its own communication protocol. At present, one of the problems encountered is: a sends data to B, assuming that the header data of frame I received by B fails to pass, and B requires A to resend, so how can I correctly deal with the remaining data of frame I sent by A.

frame format: |-- frame type-frame number (starting with 0)-- |-- data length-data-- |-trailer (check bit)-- |

uses the state machine to parse . Suppose that when parsing to the frame number, there is something wrong with this value and requires a retransmission, but there is still some data in the buffer ranging from data length to trailer .

this method is currently used to empty:

    while ((available = dataIS.available()) > 0) {
        int read = dataIS.read(new byte[available]);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

then send the instruction to resend to An after emptying is completed. Is there any better way?

there is another question: in serial communication, there may be data loss and data errors due to interference, so is it possible that there will be more data? For example, what happens when 100 bytes are actually sent, but 101 bytes are changed due to interference?

Mar.02,2021

when you confirm that there is a problem with the frame, you should immediately ask for a resend. You don't have to wait until after emptying.

Menu