[WB]: If I'm reading this right, your method quits as soon as there are no more byte in the input buffer - but the other end of the connection still has bytes to send, they just have not gotten there yet. I'm not sure that's a problem. The method quits when it's read all the bytes currently in the buffer, but when more bytes arrive, won't they set off a new SerialPortEvent? For a given SerialPortEvent, once we reach the end of the buffer there really isn't anything to do but exit the method and wait for the next event. However the program needs to make sure that data from separate DATA_AVAILABLE events eventually gets reassembled into a single
String or something. It's hard to tell what happens in the code shown - a new StringBuffer is created for each event, and data is appended to is, but then nothing is done with the StringBuffer. I'm guessing there's some code not shown here - is there a write(inputBuffer.toString()) somewhere? I think the key here is, wherever we put the data, make sure that the next time more data is available, it will get appended to the same place.
[RV]: Now end of data in Stream is signified by Ctrl/Z Character and I am able to get full data OK, good. I'm not sure what other standard protocols are out there for this, but yours seems reasonable.
but I am getting some special characters like '?' also which I am not expecting Sounds like an encoding problem. When you write
you are telling the system to treat each byte as if it's a Unicode character. That will work fine if the encoding is US-ASCII or ISO-8859-1, since those are sybsets of the first 128 and 256 Unicode values, respectively, and they fit nicely into a byte. However for several other common encodings (and many, many uncommon ones) a byte cannot simply be cast to a char to decode it to Unicode. I would say you need to find out what encoding is being used here, and use something like an InputStreamReader or a new String(byte[], String) to specify the encoding to be used to interpret each byte. If you know for sure that it's a single byte encoding this is easy.
But if a single character may take more than one byte (as is the case for UTF-8, UTF-16 and other encodings) then there's a possibility that a single character may be split across two different DATA_AVAILABLE events, which makes things a little more complex. You could just append everything to a single ByteArrayOutputStream, to be converted to a string only after you know all the data has been sent. (Except then, how will you know if ^Z has been sent? You'd need another protocol.) Or you can write all bytes read into a PipedOutputStream, and in another
thread use a PipedInputStream wrapped in an InputSreamReader to read bytes as they become available.