提升ASIO TCP螺纹.等待新样本

Boost asio tcp threaded. Wait for new sample?

本文关键字:样本 新样本 等待 ASIO TCP 螺纹 提升      更新时间:2023-10-16

i具有一个应用程序,该应用程序使用boost asio将struct作为序列化数据发送。

这一切都很好,但是我认为我正在效率低下。我要发送的实际数据仅每30ms左右更新一次,但是在发送和接收功能上,我运行的循环少于1ms。

这意味着我多次发送相同的数据。

我的问题是:

如何使这种方法更有效?

我可以轻松地在发送功能中添加条件_ WAIT以等待新示例,但是可以使接收方等待新的已发送示例吗?

发送功能是:

    void Connection()
    {
        static auto const flags = boost::archive::no_header | boost::archive::no_tracking;
        while(true)
        {
            boost::asio::io_service ios;
            boost::asio::ip::tcp::endpoint endpoint
                = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 4444);
            boost::asio::ip::tcp::acceptor acceptor(ios, endpoint);
            boost::asio::ip::tcp::iostream stream;

            // program stops here until client connects.
            acceptor.accept(*stream.rdbuf());
            connected = true;
            // Send 
            while (connected == true)
            {               
                    try
                    {
                        stream.flush();
                        boost::archive::binary_oarchive archive(stream);
                        archive << data_out; //data_out is my struct, serialized. It is updated and filled in a mutex every 30ms or so.
                    }
                    catch (...) {
                        std::cout << "connection lost, reconnecting..." << std::endl;
                        connected = false;
                    }
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));

            }
        }
    }
}

另一端接收功能是:

void Connect()
{
    while (true)
    {
        do {        
            stream.clear();
            stream.connect("127.0.0.1", "4444");
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        } while (!stream);
        bConnected = true;
        while (bConnected == true && ShutdownRequested == false)
        {
            try
            {
                stream.flush();
                boost::archive::binary_iarchive archive(stream);
                archive >> data_in; //to a struct
         }
}

一个小程序,可以尽快从套接字读取数据

int main()
{
    boost::asio::io_service io_service;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 3001));
    tcp::socket socket(io_service);
    acceptor.accept(socket);
    for (;;)
    {
        char mybuffer[1256];
        int len = socket.read_some(boost::asio::buffer(mybuffer,1256));
        mybuffer[len] = '';
        std::cout << mybuffer;
    }
  return 0;
}

我不确定如何使用iostream类,但是使用socket类,您只需调用receiveread,直到在网络上检测到字节(或async_*(如果您不想阻止这些调用的变体(。

如果您的数据结构为固定长度,则可以将其结构大小的read称为预期的字节数。如果长度可变,则需要做更多的处理。您可以将预期的大小添加为有效载荷中的前几个字节,并在循环中调用receive,直到收到该数字为止。

如果您尚未检查它们,则在Boost文档中有一个很好的示例。我建议查看聊天和回声示例。