Check if boost::asio buffer data is present before read()

↘锁芯ラ 提交于 2019-12-12 04:40:03

问题


I'm trying to port a piece of software I wrote with Unix sockets to a version with TCP sockets, using boost::asio. The program is intended to run on a Linux machine.

In the earlier version of the code (using Unix sockets) I used a simple check to see if there was new data on the socket buffer, and then proceeding with reading predictably structured data:

    ioctl(s_c, FIONREAD, &socketstatus);
    while (socketstatus > 0)
    {// do receive stuff
    ioctl(s_c, FIONREAD, &socketstatus);}

Is there any way to do something similar with boost::asio? Or some better alternatives?

Thank you in advance CB


回答1:


Use bytes_readable, this implements what you want.

Implements the FIONREAD IO control command.

boost::asio::ip::tcp::socket socket(io_service); 
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();



回答2:


You can extract the native descriptor from a boost::asio::ip::tcp::socket using the native() method, which should work just fine with your existing code.

Though, I question your motivation for doing this. The Asio event reactor implements polling mechanics using epoll on Linux. There should be no need to poll a socket for reading or writing outside of the io_service event loop.



来源:https://stackoverflow.com/questions/6748412/check-if-boostasio-buffer-data-is-present-before-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!