I would like to create client/server communication programs pair using Boost ASIO + SSL. So I started off with the examples provided by boost, and I learned how that works, and I'm almost ready to develop my communication protocol, except that there's one problem.
So starting from this example, I'm modifying the handle_read()
callback function after the handshake. The following is my code. My only modification is: Add another callback function called startComm()
, which will start the communication.
void handle_read(const boost::system::error_code& error,
size_t bytes_transferred)
{
if (!error)
{
std::cout << "Reply: ";
std::cout.write(reply_, bytes_transferred);
std::cout << "\n";
boost::asio::async_write(socket_,
boost::asio::buffer(std::string("Now?")),
boost::bind(&SSLClient::startComm, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else
{
std::cout << "Read failed: " << error.message() << "\n";
}
}
void startComm(const boost::system::error_code& error,
size_t bytes_transferred)
{
if (!error)
{
std::cout << "Reply: ";
std::cout.write(reply_, bytes_transferred); //problem here, bytes transferred should contain the number of received chars not number of written chars
std::cout << "\n";
}
else
{
std::cout << "Read failed: " << error.message() << "\n";
}
}
In the async_write()
above, there's an argument boost::asio::placeholders::bytes_transferred
which parametrizes my callback function to provide the number of bytes that were sent to the server. Now I would like to know the number of bytes the server responded with. How can I do that in my simple example?
Thanks. If you require any additional details, please ask.
The
write
call sends data.Since it doesn't, at all, receive data the number of bytes received is by definition 0.
If you want to receive data, use
(async_)read
and it will tell you the number of bytes received.These call backs use the same placeholder (
bytes_transferred
) but it carries different meaning depending on the direction of the transfer that has been completed.Here's a solution that technically does what you want: define an extra parameter of
startComm
and bind it (not with a placeholder).Note that I still think you might mistakenly expect
async_write
to receive a reply, which (obviously?) isn't the case