Boost logo

Boost Users :

Subject: [Boost-users] Terminate an io_service properly
From: Robert Gruendler (doobre_at_[hidden])
Date: 2009-08-03 17:31:01


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;
}



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net