我有一个简单的TCP服务器,其中一个线程带有asio循环,还有一个线程池来进行计算。我可以听连接在主线程中写一些东西。但是我等不及工作线程的回答,因为连接被接受后立即关闭。
我尝试使用截止时间计时器,但由于某种原因,它立即因“异常终止操作”错误而被调用。
我要实现的整个过程是:
接受连接
写一些东西
将任务发送到工作者池
等待工作者的答案(我正在使用线程安全队列从工作者池中读取消息)
将答案写到套接字
紧密连接
这是我的代码
class tcp_connection
: public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& io_service)
{
return pointer(new tcp_connection(io_service));
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
message_ = "Write me in 5 sec";
boost::asio::deadline_timer t(service_, boost::posix_time::seconds(5));
t.async_wait(boost::bind(&tcp_connection::writeAfter, shared_from_this(), boost::asio::placeholders::error));
}
private:
tcp_connection(boost::asio::io_service& io_service)
: service_(io_service), socket_(io_service)
{
}
void writeAfter(const boost::system::error_code&) {
std::cout << "writing to socket" << std::endl;
boost::asio::async_write(socket_, boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_write(const boost::system::error_code& /*error*/,
size_t /*bytes_transferred*/)
{
}
boost::asio::io_service &service_;
tcp::socket socket_;
std::string message_;
};
编辑:调试日志
@asio|1462018696.996630|0*1|deadline_timer@0x7ffd9dd40228.async_wait
@asio|1462018696.996675|0|deadline_timer@0x7ffd9dd40228.cancel
@asio|1462018696.996694|0*2|socket@0x7ffd9dd403e0.async_accept
@asio|1462018696.996714|0*3|deadline_timer@0x7ffd9dd40408.async_wait
@asio|1462018696.996736|>1|ec=system:125
正如我们所看到的,取消是在计时器上调用的,但是我的代码中没有单个取消,所以我不知道为什么要调用它。
非常感谢您的帮助
最佳答案
创建tcp_connection
后,您还在听其他连接吗?
由于尚未为新连接调用async_read
或async_read_some
,因此该线程的io_service.run()
可能已经完成...
如果在deadline timer
构造函数中启动tcp_connection
,它将使io_service.run()
继续运行并发送消息。