Hi,
i'm trying to create a simple socket server wich should be able to shut down when receiving a specific message.
I've tried to alter the blocking tcp echo server example of the boost::asio library, but i'm not sure
how to properly end the main "listening" loop from within the session thread.
here's the modified asio example. when i try to close the acceptor from within the session thread,
i get an exception "The file handle supplied is not valid". i assume this is the wrong
place to close the acceptor / stop the io_service, but i don't know where else i can do this:
using boost::asio::ip::tcp;
const int max_length = 1024;
typedef boost::shared_ptr<tcp::socket> socket_ptr;
boost::asio::io_service io_service;
tcp::acceptor* acceptor;
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.
std::string message = data;
if (message.compare("SHUTDOWN") == 0) { //how to terminate the server through an incoming message ?
acceptor->close();
io_service.stop();
}
boost::asio::write(*sock, boost::asio::buffer(data, length));
}
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}
void server(boost::asio::io_service& io_service, short port)
{
acceptor = new tcp::acceptor(io_service, tcp::endpoint(tcp::v4(), port));
std::cout << "server started" << std::endl;
for (;;)
{
if (acceptor->is_open()) {
socket_ptr sock(new tcp::socket(io_service));
acceptor->accept(*sock);
boost::thread t(boost::bind(session, sock));
}
else break;
}
std::cout << "server stopped";
}
int main(int argc, char* argv[])
{
try
{
server(io_service, 22222);
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
delete acceptor;
return 0;
}