我正处于使用boost asio构建和测试TCP套接字客户端的早期阶段。我注意到,如果boost套接字与服务器建立连接,如果我连接服务器时关闭服务器(测试boost如何响应已关闭的连接),然后使用async_write向服务器写入消息,则没有任何反应一点都不永远不会调用异步写入处理程序方法(我原以为它会被调用并出现错误)。 (如果套接字没有断开连接,则会正确调用异步写入处理程序方法。)
更新
添加deadline_timer以检查是否在异步写入处理程序之前超时 我现在在写处理程序方法中遇到错误。它似乎以某种方式使deadline_timer也使用io_service的线程现在让错误冒泡到处理程序方法。我还不能解释这个......
代码如下所示:
comm_mgr(server_info& info, io_service& service): server_info_(info), io_service_(service), timer_(service)
{
DEBUG("comm_mgr.ctor()");
}
void start(void)
{
DEBUG("start(): starting connect() method call...");
connect();
DEBUG("start(): starting thread to run io_service::run()");
t_ = new boost::thread(boost::bind(&io_service::run, &io_service_));
timer_.async_wait(boost::bind(&comm_mgr::check_write_timeout, this));
}
void connect()
{
tcp::resolver resolver(io_service_);
tcp::resolver::query query(server_info_.host, server_info_.port);
tcp::resolver::iterator iterator = resolver.resolve(query);
INFO("connect(): resetting socket and calling async_connect with handle_connect callback. connecting to: " << server_info_.host << ":" << server_info_.port);
socket.reset(new tcp::socket(io_service_));
socket->async_connect(*iterator, boost::bind(&comm_mgr::handle_connect, this, boost::asio::placeholders::error, ++iterator));
}
void send(EZXMsg& msg)
{
const char* encoded = msg.api_msg(0);
size_t bytes = std::strlen(encoded);
timer_.expires_from_now(boost::posix_time::seconds(30));
boost::asio::async_write(*socket, boost::asio::buffer(encoded, bytes), boost::bind(&comm_mgr::handle_write, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void handle_write(const boost::system::error_code& error, std::size_t bytes_transferred)
{
if (!error)
{
LOG4CXX_DEBUG(logger, "handle_write(): sent bytes" << bytes_transferred);
} else {
LOG4CXX_ERROR(logger, "handle_write(): error. ex=" << error);
}
}
为什么写入方法在套接字关闭时写入时没有注册任何错误?