我有两节课: Form1中 async_srv
当我启动应用程序时,Form1创建async_srv实例。 并且听我的插座,所有收到的数据发送到主班并从她那里回复。 当得到-1时,我想要destoy接受器/服务/线程和我的应用程序。 但这不会发生。 有什么建议吗?
我的async_srv.h
#include "Form1.h"
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
typedef boost::shared_ptr<boost::asio::ip::tcp::socket> socket_ptr;
typedef boost::shared_ptr<boost::asio::ip::tcp::acceptor> acc_ptr;
class async_srv
{
private:
boost::thread* srv_thread;
boost::asio::streambuf response;
std::stringstream s;
int stop;
TForm* ourForm;
boost::shared_ptr<boost::asio::io_service> m_ioservice;
protected:
void start();
void start_accept(acc_ptr acc,socket_ptr sock);
void handle_accept(acc_ptr acc, socket_ptr sock);
public:
__fastcall async_srv(TForm* Form1);
void kill();
};
我的async_srv.cpp
fastcall async_srv::async_srv(TForm* Form1): m_ioservice(boost::make_shared<boost::asio::io_service>())
{
//create Pointer to main form
ourForm = Form1;
//create thread to async recieve for realease this class
srv_thread = new boost::thread(boost::bind(&async_srv::start, this));
}
void async_srv::start()
{
//create acceptor, and socket.
acc_ptr acc(new boost::asio::ip::tcp::acceptor(*m_ioservice, ep));
socket_ptr sock(new boost::asio::ip::tcp::socket(*m_ioservice));
//start_accept
start_accept(acc,sock);
m_ioservice->run();
}
void async_srv::start_accept(acc_ptr acc,socket_ptr sock)
{
// async accept
acc->async_accept(*sock, boost::bind(&async_srv::handle_accept, this, acc, sock));
}
void async_srv::handle_accept(acc_ptr acc, socket_ptr sock)
{
//loop for recieve data
while (boost::asio::read(*sock, response, boost::asio::transfer_at_least(1), error))
s << &response;
if (s.str() != "")
{
//recieve answer from main
stop = ourForm->update(s.str());
if(stop == -1)
{
//kill our class and application
acc->close();
kill();
Application->Terminate();
return;
}
}
s.str(std::string());
response.consume(response.size());
start_accept(acc,sock);
}
void async_srv::kill()
{
m_ioservice->stop();
srv_thread->~thread();
}
答案 0 :(得分:1)
如果您想停止接受新连接 - 请将接受者作为成员并在需要时将其关闭:
void async_srv::kill()
{
// avoid closing from another thread
m_acceptor.get_io_service().post(()[this] { m_acceptor->close(); });
}
如果m_ioservice
仅为接受者提供服务,那么关闭它会导致async_accept-->handle_accept-->...
链断开并最终退出m_ioservice::run()
,因为它已用完。 (当然,你不应该致电~thread
。)