我有一个应用程序,使用boost asio将结构作为序列化数据发送。

一切都很好,但是我认为我的运行效率很低。
我发送的实际数据仅每30毫秒左右更新一次,但是在发送和接收功能上,我正在运行一个不到1毫秒的循环。

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

我的问题是:

我如何使这种方法更有效?

我可以轻松地在send函数中添加condition_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] = '\0';
        std::cout << mybuffer;

    }

  return 0;
}

10-08 14:04