当我放置断点时,TCP 写入和读取命令给出不同的结果

TCP write and read commands give different results when I put breakpoints

我想从 C# 中的秤中获取重量,所以我为此使用了 TCP 连接。

这是我的代码,

private TcpClient _client;
public NetworkStream Stream { get; private set; }

public ScalesService()
{
    _client = new TcpClient();
}

async public Task<string> TestRead()
{
    var responseLength = 1024;
    var readResponse = new byte[responseLength];

    string result = "";

    Console.WriteLine("connecting...");
    await _client.ConnectAsync("10.100.200.70", 1182);
    Console.WriteLine("connected!");

    Stream = _client.GetStream();

    var cmdUser = Encoding.ASCII.GetBytes("user admin\n");
    await Stream.WriteAsync(cmdUser, 0, cmdUser.Length);

    var countCmdUser = await Stream.ReadAsync(readResponse, 0, readResponse.Length);
    var responseCmdUser = Encoding.ASCII.GetString(readResponse, 0, countCmdUser);

    var cmdRead = Encoding.ASCII.GetBytes("read wt0501\n");

    await Stream.WriteAsync(cmdRead, 0, cmdRead.Length);

    var countCmdRead = await Stream.ReadAsync(readResponse, 0, readResponse.Length);
    var responseCmdRead = Encoding.ASCII.GetString(readResponse, 0, countCmdRead);

    //result = responseCmdRead;

    if (!string.IsNullOrEmpty(responseCmdRead))
    {
        // Expected Return: [00R001~       10300~]
        var responseArray = responseCmdRead.Split('~');
        if (responseArray.Length >= 2)
        {
            var weightString = responseArray[1];

            float grossNetWt;
            result = weightString;
            //if (float.TryParse(weightString, out grossNetWt))
            //{
            //    result = grossNetWt;
            //}
        }
    }

    var cmdQuit = Encoding.ASCII.GetBytes("quit\n");
    await Stream.WriteAsync(cmdQuit, 0, cmdQuit.Length);

    return result;
}

似乎流不等给我完整的答案。无论是否设置断点,我都会得到不同的结果。有更好的方法吗?我在想 await 会是一个很好的解决方案。

如评论中所述,TCP/IP 套接字是 字节 的流,而不是 数据包 的流。如果你想 read/write 整条消息,你需要使用某种 message framing.

由于您已经拥有设备,因此消息帧的类型应记录在设备的协议规范中。从您发布的示例代码来看,它似乎使用了 \n 的消息定界符。所以你需要有一个读取循环,将字节添加到缓冲区,直到你看到 \n.