boost中使用Asio,对端关闭时回调函数被调用两次的问题


在使用boost的asio实现异步网络服务器时,对每一个连接的socket注册回调函数。当对端关闭时,本地的读回调函数得到调用,在关闭socket之后,读回调函数再次得到调用。网上查了下资料,发现这类的中文资料不多,而英文的资料,针对的也不是出现这个问题的描述。所以在这里做个记录。

    来源于https://stackoverflow.com/questions/35393015/how-do-you-correctly-close-sockets-in-boostasio的资料,告诉我们,当调用socket的close方法时,要注意以下几点:


  • 如果是在多线程环境下,close调用应该包装在strand 中,不然会crash. 查看boost strand documentation.
  • 不管你什么时候调用close,一定要记得io_service


  • If you have threads, this call should be wrapped with strand or you can crash. See boost strand documentation.
  • Whenever you do close keep in mind that io_service can already have queued handlers. And they will be called anyway with old state/error code.
  • close can throw an exception.
  • close does NOT includes ip::tcp::socket destruction. It just closes the system socket.
  • You must manage object lifetime yourself to ensure objects will be destroyed only when there is no more handlers. Usually this is done with enable_shared_from_this on your Connectionor socket object.

close后,会触发该连接的所有异步回调函数,并且传递错误码,错误码为, boost::asio::error::operation_aborted


评论

发表评论