【问题标题】:how to ensure that remote peer receive all data before call asio socket close() function如何确保远程对等方在调用 asio socket close() 函数之前接收到所有数据
【发布时间】:2012-06-06 09:53:32
【问题描述】:

问题是当我调用 asio 套接字函数 close() 来关闭套接字时, 之前发送的数据全部丢失!

【问题讨论】:

    标签: c++ boost-asio send shutdown


    【解决方案1】:

    为确保在调用close 之前写入所有数据,您应该使用io_service 的事件循环。

    以 asio 的chat client 为例说明如何操作:

    void write(const chat_message& msg)
    {
      io_service_.post(boost::bind(&chat_client::do_write, this, msg));
    }
    
    void close()
    {
      io_service_.post(boost::bind(&chat_client::do_close, this));
    }
    

    通过posting 对事件循环的实际写入,您正在委派确保一切以正确顺序发生的工作。

    如果您想在关闭套接字之前确保远程端点已收到所有内容,则需要构建某种协议,即让远程端点发送一条消息来确认。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多