提升ASIO TCP螺纹.等待新样本
Boost asio tcp threaded. Wait for new sample?
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
类,您只需调用receive
或read
,直到在网络上检测到字节(或async_*
(如果您不想阻止这些调用的变体(。
如果您的数据结构为固定长度,则可以将其结构大小的read
称为预期的字节数。如果长度可变,则需要做更多的处理。您可以将预期的大小添加为有效载荷中的前几个字节,并在循环中调用receive
,直到收到该数字为止。
如果您尚未检查它们,则在Boost文档中有一个很好的示例。我建议查看聊天和回声示例。
相关文章:
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 使用源读取器从网络摄像头源获取 H264 样本
- 当相机接近模型时,SSAO样本内核会导致性能下降?
- 如何从 std::set 绘制 n 个元素的样本
- 如何通过一次运行将多个输入样本馈送到C++张量流模型
- 如何测量一个音频样本中的低音量
- 如何从 avi 文件中抓取所有帧 - 如何修改 MS 样本采集卡样本
- 为什么当只有样本计数不同时avcodec_fill_audio_frame返回 -22?
- 在QtMultimedia的QAudioFormat中为24位,32位和64位音频选择哪种样本类型(而不是大小)?
- 提升ASIO TCP螺纹.等待新样本
- webRTC : 如何通过从WAV文件获得的样本将webRTC的VAD应用于音频
- 具有固定样本空间的排列算法
- 数据集(和样本)何时在 boost::test 中销毁?
- 媒体基础获得视频文件的精确帧(样本)计数
- Visual样本存储过程从C 程序执行
- 是否可以从SFML中的音频样本中左右通道分开
- Runge-Kutta第四阶粒子对流代码样本
- 犰狳媒介类的RCPP犰狳样本
- 为什么 SDL2 为音频样本提供的缓冲区不够大
- 如何将音频字节转换为样本