1

I have a problem with the function async_read_some(). I am running cyclicly the function receiveAsyncWithTimeout() by a timer.

Expected working The function receiveAsyncWithTimeout() should read all messages from my server.

Problems

  1. bytesTransferred and bytesReadable are different.
  2. Messages are received weirdly. First one frame, after about 10 seconds the rest.

Boost version: 1.77

output:

readHandle bytesReadable: 0 bytesTransferred: 1112

pseudocode:

class TlsSocket 
{
public:
    TlsSocket(boost::asio::io_context &io_context,
              const std::string &endpoint);
private:
    boost::asio::io_context &_iocontext;
    boost::asio::ssl::context _ctx;
    boost::asio::ssl::stream<boost::asio::ip::tcp::socket> _socket;
    std::vector<uint8_t> _recvBuffer;
    std::vector<uint8_t> _sendBuffer;
    size_t _bytesReadable{0};
}

void TlsSocket::readHandle(const boost::system::error_code &ec, std::size_t bytesTransferred)
{
    if(_bytesReadable == 0 && bytesTransferred > 0)
    {
        std::cout << "readHandle ERROR bytesReadable: " << _bytesReadable
                  << " bytesTransferred: " << bytesTransferred << std::endl;
        return;
    }

/// .. any code
}

void TlsSocket::receiveAsyncWithTimeout()
{
    boost::asio::socket_base::bytes_readable command(true);
    _socket.lowest_layer().io_control(command);
    _bytesReadable = command.get();
    
     _socket.async_read_some(boost::asio::buffer(_recvBuffer),
                            boost::bind(&TlsSocket::readHandle,
                                        this,
                                        boost::asio::placeholders::error,
                                        boost::asio::placeholders::bytes_transferred));
}

Michał Hanusek
  • 199
  • 3
  • 13
  • In general, framing and delivery can not be relied on. TCP stacks are free to re-arrange for optimal resource utilization (both kernel, on the wire etc). There are a number of options that can tune this (TCP_NODELAY, QUICKACK e.g.) as well as sysctls and sometimes your physical adaptor(s). SSL adds a layer of indirection on top of all that. If you have trouble you can always give a self-contained, working example and we can reproduce the issue/suggest remedies. However, none of us can run pseudo-code (not even you) so for now you'll have to do with general comments like this. – sehe May 28 '23 at 21:38

0 Answers0