2

我正处于使用 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);
    }
}

为什么在套接字关闭时写入方法不会记录任何错误?

4

0 回答 0