Socket.Receive() 仅在逐步调试代码时才按预期工作

Socket.Receive() works as expected only when debug the code step by step

我是套接字编程的新手。我有一个用 C# 编写的小应用程序,它使用 COM 端口连接到 "key mapper" 设备,该设备仅在应用程序发送匹配命令时才响应。例如:如果我需要从映射器获取一些引脚号,我发送了一个十六进制命令。然后我收到正确的回复。现在,我正在尝试使用具有设备唯一 IP 地址的套接字连接来执行相同的操作 activity,如下所示。

private void button1_Click(object sender, EventArgs e)
{
    byte[] sendCommand = new byte[] { 0x02, 0x24, 0x31, 0x95, 0x0A, 0x0D, 0x03 };
    byte[] ReceivedVal = new byte[1024];
    IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.178.170"), 10001);
    Socket senderNew = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream, ProtocolType.Tcp);

    waitLoop(5);
    try
    {
        senderNew.Connect(ipEndPoint);
    }
    catch(SocketException socProblem)
    {
        Console.WriteLine(socProblem.Message.ToString());
    }
    waitLoop(5);
    int test = senderNew.Receive(ReceivedVal);
    Console.Write("Starting bytes read : ");
    Console.WriteLine(test.ToString());
    waitLoop(5);

    int bytesSent = senderNew.Send(sendCommand);
    waitLoop(5);
    Console.WriteLine("Socket connected to {0}", senderNew.RemoteEndPoint.ToString());
    int bytesRec = senderNew.Receive(ReceivedVal);
    Console.Write("data bytes read : ");
    Console.WriteLine(bytesRec.ToString());
    waitLoop(5);

    QueryAllCodeResponseHandler(ReceivedVal);
    waitLoop(5);
    Console.Write("Number of Pin Codes read: ");
    Console.WriteLine(PinCodes.Length.ToString());
    senderNew.Close();
    GC.Collect();
    PinCodes = null;
    ReceivedVal = null;
    ipEndPoint = null;
    GC.Collect();
}

预期结果如下:

当我逐行调试它时,它完全可以正常工作。但是如果我 运行 它直接没有任何调试点或逐行跳过调试,我只会得到 2 个引脚或 0 个引脚。然后我尝试在这次不成功的尝试之后使用第 3 方应用程序写入,并意识到它收到了上次尝试的其余引脚。谁能帮我找出问题所在?

正如已经指出的那样,您的代码留下了一些问题,但是(假设您的调试步骤是准确的)您似乎只是依靠 TCP 协议来决定何时完成接收响应。

您要连接的设备应使用应用程序定义的协议以允许对其进行查询。例如,初始响应将包含整个预期响应的字节数,或者将使用特定字符来指示响应的结束,有无限种方式。

正确的实现会循环多次 receives() 直到数据被完全接收(或超时到期)。

换句话说,设备发送数据的速度似乎比您想象的要慢得多,直接 运行(没有调试停止)只会捕获部分响应。