C# 可靠地读取蓝牙流(InTheHand 32 英尺)



我在可靠地读取蓝牙流方面遇到问题。这是我第一次使用蓝牙连接。该应用程序通过蓝牙模块与Arduino通信。它将发送命令并获得响应。
例如,响应应如下所示:

100,200,300,400这就是我得到的:

1如果我得到另一个响应(也如果它看起来完全不同),我会得到之前请求的其余响应:

00,200,300,400有时我甚至会得到空洞的回应。

以下是我用来读取和写入流的代码:

    void BluetoothClientConnectCallback(IAsyncResult result)
    {
        try
        {
            BluetoothClient client = (BluetoothClient)result.AsyncState;
            client.EndConnect(result);
            NetworkStream stream = client.GetStream();
            stream.ReadTimeout = 1000;
            _frm.printMsg("Connected!", false);
            byte[] receive = new byte[1024];
            while (true)
            {
                while (!ready) ;
                if (stopConnection == true)
                {
                    return;
                }
                try
                {
                    stream.Write(message, 0, message.Length);
                }
                catch
                {
                    _frm.printMsg("Error occurred while writing stream.", true);
                }
                try
                {
                    if (Commands.awaitresponse == true)
                    {
                        Array.Clear(receive, 0, receive.Length);
                        readMessage = "";
                        do
                        {
                            stream.Read(receive, 0, receive.Length);
                            readMessage += Encoding.ASCII.GetString(receive);
                        }
                        while (stream.DataAvailable);
                        _frm.printMsg("Received: " + readMessage, false);
                        Commands.awaitresponse = false;
                    }
                }
                catch
                {
                    _frm.printMsg("Error occurred while receiving stream.", true);
                }
                ready = false;
            }
        }
        catch
        {
            _frm.printMsg("Error occurred while connecting.", true);
        }
    }

我研究了一段时间,但无法找到解决方案。

经过更多的调试和测试,我自己找到了解决方案。
在阅读流之前,我添加了 1 个延迟Thread.Sleep(1000);
所有包现在都正确显示为红色。

最新更新