the problem comes from the following for loop:
for(;;)
{
boost::asio::async_write(sock, boost::asio::buffer(teststr,102),
boost::bind(&handle_write,
boost::asio::placeholders::bytes_transferred,
boost::asio::placeholders::error));
}
an async_write operation may be begin before the completion
of previous async_write which is not allowed.
REF: async_write
the correct way is to eliminate the for loop and call async_write in the handle_write function:
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
using boost::asio::ip::tcp;
char teststr[]="1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\n";
void handle_write(tcp::socket* sock, size_t num_bytes, boost::system::error_code e)
{
static int i=0;
if(!e)
{
std::cout<<i++<<std::endl;
boost::asio::async_write(*sock, boost::asio::buffer(teststr,102),
boost::bind(&handle_write, sock,
boost::asio::placeholders::bytes_transferred,
boost::asio::placeholders::error));
}
else
{
std::cout<<"Error: "<<e.message()<<std::endl;
exit(1);
}
}
int main()
{
boost::asio::io_service ios;
tcp::resolver r(ios);
tcp::resolver::query q(tcp::v4(), "127.0.0.1", "41000");
tcp::resolver::iterator it = r.resolve(q);
tcp::socket sock(ios);
boost::asio::connect(sock, it);
boost::thread t(boost::bind(&boost::asio::io_service::run,&ios));
boost::asio::async_write(sock, boost::asio::buffer(teststr,102),
boost::bind(&handle_write, &sock,
boost::asio::placeholders::bytes_transferred,
boost::asio::placeholders::error));
t.join();
}