boost asio串行端口-async_read_some不读取数据

时间:2018-09-29 12:46:36

标签: c++ serial-port boost-asio

我创建了一个简单的类,它读取一个串行端口:

class SerialPort
{
public:
    SerialPort(const std::string& port): serialPort_(io_service_, port){}

    void ReadAsync()
    {
        serialPort_.async_read_some(boost::asio::buffer(buffer_),
                                    boost::bind(&SerialPort::ReadComplete,
                                    this, boost::asio::placeholders::error,
                                    boost::asio::placeholders::bytes_transferred));

        thread_ = boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_));
    }

    void ReadComplete(const boost::system::error_code& error, size_t bytesTransferred)
    {
        std::cout << "Bytes transferred: " << bytesTransferred << std::endl;
        buffer_.clear();

        ReadAsync();
    }

    void Read()
    {
        char c = '\0';
        boost::asio::read(serialPort_, boost::asio::buffer(&c, 1));
        std::cout << c << std::endl;
    }

private:

    boost::asio::io_service io_service_;
    boost::asio::serial_port serialPort_;
    boost::thread thread_;
    std::vector<std::uint8_t> buffer_;
};

Read方法工作正常,但是当我使用ReadAsync时,总是使用 bytesTransferred == 0 来调用ReadComplete,这是怎么回事?

0 个答案:

没有答案