From e368ad2efb64395716e1ecd0bac92c2767009984 Mon Sep 17 00:00:00 2001 From: Adam Gu Date: Tue, 31 Jul 2018 10:50:11 +0800 Subject: [PATCH] Close the socket after shutdown. --- example/rest_book_client/main.cc | 2 -- webcc/http_connection.cc | 34 ++++++++++++++++++++------------ webcc/http_connection.h | 3 +++ 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/example/rest_book_client/main.cc b/example/rest_book_client/main.cc index 9808306..edc641c 100644 --- a/example/rest_book_client/main.cc +++ b/example/rest_book_client/main.cc @@ -208,7 +208,5 @@ int main(int argc, char* argv[]) { list_client.ListBooks(); - getchar(); - return 0; } diff --git a/webcc/http_connection.cc b/webcc/http_connection.cc index c00b570..4ecb179 100644 --- a/webcc/http_connection.cc +++ b/webcc/http_connection.cc @@ -100,23 +100,31 @@ void HttpConnection::AsyncWrite() { // This is ensured by Asio. void HttpConnection::WriteHandler(boost::system::error_code ec, std::size_t length) { - if (!ec) { - LOG_INFO("Response has been sent back, length: %u.", length); - - // Initiate graceful connection closure. - LOG_INFO("Close socket gracefully..."); - // TODO: shutdown(both) should be identical to close(). - boost::system::error_code ec; - socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); - if (ec) { - LOG_ERRO("Failed to close socket."); - } - } else { - LOG_ERRO("Sending response error: %s", ec.message().c_str()); + if (ec) { + LOG_ERRO("Socket write error: %s", ec.message().c_str()); if (ec != boost::asio::error::operation_aborted) { Close(); } + } else { + LOG_INFO("Response has been sent back, length: %u.", length); + + Shutdown(); + Close(); // Necessary even after shutdown! + } +} + +// Socket close VS. Shutdown: +// https://stackoverflow.com/questions/4160347/close-vs-shutdown-socket +void HttpConnection::Shutdown() { + LOG_INFO("Shutdown socket..."); + + // Initiate graceful connection closure. + boost::system::error_code ec; + socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); + + if (ec) { + LOG_ERRO("Socket shutdown error: %s", ec.message().c_str()); } } diff --git a/webcc/http_connection.h b/webcc/http_connection.h index 3d8896c..de9caaa 100644 --- a/webcc/http_connection.h +++ b/webcc/http_connection.h @@ -45,6 +45,9 @@ class HttpConnection : public std::enable_shared_from_this { void AsyncWrite(); void WriteHandler(boost::system::error_code ec, std::size_t length); + // Shutdown the socket. + void Shutdown(); + // Socket for the connection. boost::asio::ip::tcp::socket socket_;