从串口读取时,随机算法溢出

时间:2015-03-11 21:55:13

标签: c#

我正在做的是让用户输入字符串,创建包含数据的数据包,然后将字符串发送到串行端口。然后我通过环回连接器读取我发送的数据。我的发送工作完美无缺,但我的接收是随机抛出算术溢出异常。

我随机说,因为它不是一直发生的。例如,我发送消息“hello”两次。第一次工作正常,第二次输出任何内容并抛出异常。我重新启动我的程序,再次运行代码,并发送hello只接收“地狱”然后异常。在极少数情况下,我会在异常之前连续3或4次收到数据包而没有错误。

以下是我的相关代码:

public void receivePacket(object sender, SerialDataReceivedEventArgs e)
{
    byte[] tempByte = new byte[2];
    int byteCount = 0;

    while (serialPort1.BytesToRead > 0)
    {
        if (byteCount <= 1)
        {
            tempByte[byteCount] = (byte)serialPort1.ReadByte();
        }

        if (byteCount == 1)
        {
            receivedString = new byte[tempByte[byteCount]];
            receivedString[0] = tempByte[0];
            receivedString[1] = tempByte[1];
        }
        else if (byteCount > 1)
        {
            byte b = (byte)serialPort1.ReadByte();
            receivedString[byteCount] = b;
        }

        byteCount++; 

    }

    int strLen = (byteCount - 3);

    tempByte = new byte[strLen];

    int newBit = 0;

    for (int i = 2; i <= strLen+1; i++)
    {
        tempByte[newBit] = receivedString[i];
        newBit++;
    }

    string receivedText = encoder.GetString(tempByte);

    SetText(receivedText.ToString());
}

我很清楚我使用byteCount(我用来遍历字节数组)的实现是相当草率的。当我逐步执行代码时,我发现当我收到错误byteCount == 1时,这使得strLen为负数(因为strLen为byteCount - 3,这是因为数据包包含标题,长度,和CRC即byteCount - 3 == # of actual data bytes received)。这导致tempByte的大小为-2,这引发了我的异常。但是,我很难弄清楚为什么将byteCount设置为1。

此后的代码基本上只遍历数组的数据部分,将其复制到tempByte中,然后发送给函数以将文本附加到另一个线程中。

1 个答案:

答案 0 :(得分:1)

我猜测byteCount是1,因为你只收到一个字节 - 或者更确切地说,你在第二个字节到达缓冲区之前处理了第一个字节。

如果没有人等待,ReadByte函数会等待一段时间才能到达。

也许如果不是检查BytesToRead,你做了更像这样的事情:

byte headerByte = serialPort1.ReadByte();
byte length = serialPort1.ReadByte();
receivedString = new byte[length];
receivedString[0] = headerByte;
receivedString[1] = length;
for (int i = 2; i < length; i++) {
    receivedString[i] = serialPort1.ReadByte();
}