Is it possible to do async_handshake after reading from socket prior using Boost::asio?

后端 未结 1 625
不知归路
不知归路 2021-01-28 08:24

I have a boost::asio::ssl::stream typed socket. When boost first accepts a connection to this socket, I want to peek at some byt

相关标签:
1条回答
  • 2021-01-28 09:13

    After investigating the implementation of async_handshake's buffer overload method, it appears that the buffer must already have the handshake read in.

    I attempted that but still encountered issues, I kept getting an error code saying that the SSL version was incorrect. I knew this was not the issue because not using the buffered overload of async_handshake worked fine!

    The solution was then to also limit the buffer parameter's size.

    typedef socket_type boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
    void OnAccept(std::shared_ptr<socket_type> socket)
    {
        const uint bytesToPeek = 4;
        boost::asio::mutable_buffers_1 sslBuffer(m_Buffer.data(), m_Buffer.size());
        // I'm going to read 4 bytes from the socket.
        boost::system::error_code ec;
        std::size_t readBytes = boost::asio::read(socket->next_layer(), boost::asio::buffer(sslBuffer, bytesToPeek), ec);
        if(ec) { Stop(); return; } // pseudo
    
        // Check the bytes I read in the buffer
    
        // Read in the rest of the handshake.
        std::size_t bytesOfHandshake = socket->next_layer().read_some(boost::asio::buffer(sslBuffer+bytesToPeek, 4000));
        bytesOfHandshake += bytesToPeek;
    
        // Finish the handshake.
        socket->async_handshake(boost::asio::ssl::stream_base::server, boost::asio::buffer(sslBuffer, bytesOfHandshake), &handler);
    }
    

    Note that both the read and read_some calls in this should also be made async. I just wanted to demonstrate the answer without handlers.

    0 讨论(0)
提交回复
热议问题