Boost ASIO和串口异步读取

Boost ASIO and serial port async read

我正在尝试使用 Boost ASIO 进行串行端口异步读取,当我的程序是 运行 时我必须不断收听,此外我也在收听 multicast udp reciever example I found in the Boost ASIO. Both UDP and serial receiver I am initializing with the same io_context. When I try to create serial port in my console app main program, I can compile and read from serial port but only once. So I thought I should make it into a separate class like in this example 并且可能会利用一个单独的线程。但是,即使我使用的语法与我在主程序中尝试的语法完全相同,运行 没问题,但只有一次,我仍然会遇到编译错误。当我连续(仍然异步)从 udp 端口​​数据读取时,我如何继续在串行端口上以异步方式收听。请指教。

我试图四处寻找非官方示例,但它们真的没有帮助,要么它们很差、过时或者只是不必要地复杂。我要构建的东西比这样简单得多

#pragma once
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>

class SerialComm
{
public:
    SerialComm(boost::asio::io_context& io_context, std::string& serial_port_name) :_serialport(io_context, serial_port_name)
    {
        start_receive();
    }

    ~SerialComm()
    {
    }

private:
    void start_receive()
    {
        _serialport.async_read_some(boost::asio::buffer(my_buffer, 1024),
            &SerialComm::handle_receive);
    }

    void handle_receive(const boost::system::error_code& error,
        std::size_t bytes_transferred)
    {
        if (!error)
        {
            std::cout << "Recieved:" << my_buffer << std::endl;
        }
    }

private:

    boost::asio::serial_port _serialport;
    unsigned char my_buffer[1024];
    //boost::asio::buffer<char, 1024> recv_buffer_;
};

这是我得到的错误:

1>c:\users\alam syed\documents\someproject\boost\include\boost-root\boost\asio\serial_port.hpp(746): error C2338: ReadHandler type requirements not met 1>c:\users\alam syed\documents\someproject\public\serialcomm.h(24): note: see reference to function template instantiation 'void boost::asio::serial_port::async_read_some(const MutableBufferSequence &,ReadHandler &&)' being compiled 1> with 1> [ 1>
MutableBufferSequence=boost::asio::mutable_buffers_1, 1>
ReadHandler=void (__cdecl SerialComm::* )(const boost::system::error_code &,size_t) 1> ] 1>c:\users\alam syed\documents\someproject\boost\include\boost-root\boost\asio\use_future.hpp(138): note: see reference to class template instantiation 'boost::asio::use_future_t>::std_allocator_void' being compiled 1>c:\users\alam syed\documents\someproject\boost\include\boost-root\boost\asio\use_future.hpp(146): note: see reference to class template instantiation 'boost::asio::use_future_t>' being compiled

这个问题其实很容易解决。我为像我这样的涉猎者保留它。只需使用这个:

_serialport.async_read_some(boost::asio::buffer(recv_buffer_),
            boost::bind(&SerialComm::handle_receive,
                this, boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));