我需要从设备通过telnet读取一堆行。当我开始阅读它时,设备发送数据并完成发送。问题是,当我查看收到的数据时,我可以看到一些字符丢失。有什么问题 ?
这是执行接收任务的函数:
//calling the function
string out_string = Encoding.Default.GetString(ReadFully(readStream,0));
//the function which read the data
public static byte[] ReadFully(Stream stream, int initialLength)
{ if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0 && (Byte)stream.ReadByte() != 65)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
答案 0 :(得分:0)
这是你的while循环的第二部分:
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0 &&
(Byte)stream.ReadByte() != 65) //<-- Here
你总是在每个循环中读取一个额外的字节,并且(如果它不是65)从不在任何地方存储该字节。
注意,Stream.ReadByte
:
从流中读取一个字节,将流中的位置提前一个字节 ......
(我的重点)
答案 1 :(得分:0)
如果某个字符不是65(ASCII A),则您的条件(Byte)stream.ReadByte() != 65
会丢弃该字符。