0

我需要通过 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++;
            }
        } 
4

2 回答 2

0

如果不是 65(ASCII A),您的条件(Byte)stream.ReadByte() != 65就是丢弃一个字符。

于 2013-07-08T06:39:31.387 回答
0

这是您的 while 循环的第二部分:

while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0 &&
   (Byte)stream.ReadByte() != 65)  //<-- Here

您总是在每个循环中读取一个额外的字节,并且(如果不是 65)永远不会将该字节存储在任何地方。

注意,Stream.ReadByte

从流中读取一个字节并将流中的位置提前一个字节...

我的重点

于 2013-07-08T06:36:07.037 回答