I'm using Boost::asio
to test tcp communication. I write a c++ server code and use telnet
as client to connect my server node, which are run in 2 terminals respectively.
My question is:
when connected, server can use async_write
to send data to the client, but when the server use async_read
to read data from the client, the server node crushed.
I think this problem may come from the buffer, but I don't know how to solve it.
Here are my codes:
std::vector<char> session::readResponse(const int move_id)
{
int data_size;
switch (move_id)
{
// receive data from info1
case 1:
data_size = 20;
break;
// receive data from info2
case 2:
data_size = 19;
break;
default:
data_size = 0;
break;
}
auto self(shared_from_this());
bool data_available = false;
std::vector<char> char_vector(data_size);
try
{
boost::mutex::scoped_lock scoped_locker(*mutex_);
boost::asio::async_read(
socket_,
boost::asio::buffer(char_vector, data_size),
[&](const boost::system::error_code &error, std::size_t bytes_transferred)
{
if (error)
{
data_available = false;
std::cerr << ">>> readCallback Error " << error << std::endl;
}
timeout_->cancel();
data_available = true;
});
timeout_->expires_from_now(boost::posix_time::seconds(10));
timeout_->async_wait(
[&](const boost::system::error_code &error)
{
if (!error)
{
data_available = false;
socket_.cancel();
std::cerr << ">>> Read timeout." << std::endl;
}
});
}
catch(const std::exception& e)
{
std::cerr << ">>> Read exception. " << e.what() << '\n';
}
if (data_available)
{
return char_vector;
}
else
{
throw ">>> reading timeout";
}
}
void gManualSendCommand(Server& srv)
{
while( true )
{
if(srv.getSession() == NULL)
{
}
else
{
std::cout << "Enter robot command id: ";
std::string id;
std::getline(std::cin, id);
srv.getSession()->writeCommand(std::stoi(id));
srv.getSession()->readResponse(std::stoi(id));
std::cout << "\n";
}
}
}
These codes are modified from my last project (serial port communication), and last time I did not meet this problem.
Any suggestion will be highly appreciated, thanks.
UPDATE(0811-1):
I found that my readResponse
function won't actuate the timer to wait 10s, hence, the function throws ">>> reading timeout"
.
UPDATE(0811-2): After some tests, the timer is actually actuated. However, only io callbacks get blocked by this timer, so the function quickly jumps to the if condition and return.