Mircea said:
I face with another problem with serial port. I read string bytes of
different lenghts. If the incoming string has up to 8 bytes, everything is
fine. If the incoming string has more than 8 bytes, there is a problem. For
example, I read a byte string from the serial port which is 11 bytes long.
The function read returns only the first 8 bytes and I have to perform a
second read for the other 3. This behavoiur is exactly like a TCP port. This
time I know how many bytes I expect, but there are cases when I don't know
how many bytes I get.
Yes, it is exactly a Stream, you are not guaranteed that the buffer you
pass is filled, only that at least one byte is written, or that the
stream is closed, in which case 0 bytes are returned.
Is tihs the behaviour of the serial port in C# 2, or I miss something?
How can the serial-port guess how many bytes you need to read? should it
always block untill your buffer is filled?
In the special-case of a serial-port stream, you can set a
timeout-value, s.t. Read will return if no data is not recieved within a
certain time-limit.
I use the function Read(byte[], offset, length) and doesn't matter what I
use as lenght, either BytesToRead, or length of the byte array, which is
large enough. If the expected input is more than 8 bytes, BytesToRead is
always 8 and I need some more readings.
if you wish to remain blocked while reading any amount of data, use a
helper function:
public static void FillBuffer(
Stream s, byte[] buffer, int offset, int count)
{
for ( int r = 0, i = 0; i < count; i += r )
{
r = s.Read(buffer, offset+i, count-i);
if ( r <= 0 )
throw new EndOfStreamException(
string.Format("EOS while reading {0} bytes, only got {1}",
count, i));
}
}
...
byte[] buf = ...;
FillBuffer(s, buf, 0, buf.Length);
If you have more complex requirements, you will need to encode the data
that you transmit in a protocol which you can parse chunk-by-chunk.