I have been stuck with this prolem for the past 5 hours or so.. Sorry if the question is too obvious/noob but I am noob myself when it comes to boost::asio or tcp/ip in general.
So here is the problem. I am trying to modify the blocking tcp server example :
void session(socket_ptr sock)
{
try
{
for (;;)
{
char data[max_length];
boost::system::error_code error;
size_t length = sock->read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
boost::asio::write(*sock, boost::asio::buffer(data, length));
}
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}
What I want to do is save all the chunks or the read_some method into some buffer for this example std::string and then do something with them before sending a reply back:
const int max_length = 10;
typedef boost::shared_ptr<tcp::socket> socket_ptr;
void session(socket_ptr sock)
{
std::string dataReceived = "";
try
{
for (;;)
{
char data[max_length] = {'\0'};
boost::system::error_code error;
size_t length = sock->read_some(boost::asio::buffer(data), error);
dataReceived += std::string(data, length);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
//boost::asio::write(*sock, boost::asio::buffer(&dataReceived[0], dataReceived.size()));
}
boost::asio::write(*sock, boost::asio::buffer(&dataReceived[0], dataReceived.size()));
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}
When I remove the write from inside the loop the client hangs. The dataReceived has all the data inside. The buffer is deliberately small so that read_some is called more than once. In the debugger the control never goes to the write method outside of the loop. I am probably doing something very wrong. But I am unable to find out what.
Side question:
What would be the simplest solution to have a socket connection between some UI and a backend process?