我有一个应用程序,使用boost asio将结构作为序列化数据发送。
这一切都运作良好,但我认为我运行效率不高。 我发送的实际数据每30ms左右更新一次,但在发送和接收功能上,我运行的循环时间不到1ms。
这意味着我多次发送相同的数据。
我的问题是:
如何使这种方法更有效率?
我可以在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
}
}
答案 0 :(得分:1)
尽可能快地从套接字读取数据的小程序
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;
}
答案 1 :(得分:0)