diff --git a/lib/asio_server_connection.h b/lib/asio_server_connection.h index a948965..f2dc954 100644 --- a/lib/asio_server_connection.h +++ b/lib/asio_server_connection.h @@ -88,9 +88,20 @@ class connection : public std::enable_shared_from_this>, void start() { boost::system::error_code ec; + auto make_writefun = [this] { + return [weak = std::weak_ptr{this->shared_from_this()}]() { + auto self = weak.lock(); + // If connection already got destroyed, the socket is already closed in particular. + // Therefore we can simply ignore further calls to write. + if (self) { + self->do_write(); + } + }; + }; + handler_ = std::make_shared( GET_IO_SERVICE(socket_), socket_.lowest_layer().remote_endpoint(ec), - [this]() { do_write(); }, mux_); + make_writefun(), mux_); if (handler_->start() != 0) { stop(); return;