Boost logo

Boost Users :

Subject: Re: [Boost-users] [asio] Removing server socket from service
From: michi7x7 (mailing-lists_at_[hidden])
Date: 2010-11-03 14:34:02


Am 02.11.2010 22:38, schrieb Sakharuk, Vladimir:
>
> I have one thread how runs io_service.
> I have 2 servers (tcp) ports with all corresponded acceptor and bunch
> of sockets connected to both ports.
>
> I am looking into the way to stop just one server but still run the
> other one.
> I have implemented a "hard" way to stop server: remove acceptor,
> cancel/close sockets, that will trigger all read/write asynchronous
> callbacks, wait till they all done.
>
Hi,

this could be done much easier:
- First use shared_from_this() for your client-connections
- Let the main-server emit a close-signal, to which the clients connect
(don't forget to disconnect on destruction)

Example:

class server
{
   public:
     void on_connect()
     {
         shared_ptr<client> client = new client(); //you will have to
construct this prior to this (to get the soccet for accept())
         client->set_close_signal(signal_close_.connect(&client::close,
client);
         client->start();
      }

     void close()
     {
       socket_.close();
       signal_close_();
     }
   private:
     signals2::connection signal_close_;
     tcp::acceptor socket_;
};

class client : public enable_shared_from_this<client>
{
   public:
     void start() {} //start the client using shared_from_this()

     void set_close_signal(signals2::connection conn)
     {
       conn_ = conn; //well... never tried this, look into the signals2-docs
     }

     void close()
     {
       socket_.close();
     }
   private:
     tcp::socket socket_;
     signals2::scoped_connection conn_; //I think that's the name
};

The scoped_connection is used to disconnect the close-signal on
client-destruction (obvious, I think..)

Regards,

michi7x7

PS: Note that there might still be client-connections left on
close()-call, but there should be no async-action executed because error
is set.
PPS: Use weak_ptr to store a list of clients in the server



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