@@ -537,12 +537,6 @@ namespace libp2p::connection {
537537
538538 SL_DEBUG (log (), " closing connection, reason: {}" , notify_streams_code);
539539
540- write_queue_.clear ();
541-
542- if (reply_to_peer_code.has_value () && !connection_->isClosed ()) {
543- enqueue (goAwayMsg (reply_to_peer_code.value ()));
544- }
545-
546540 Streams streams;
547541 streams.swap (streams_);
548542
@@ -560,6 +554,14 @@ namespace libp2p::connection {
560554 if (closed_callback_) {
561555 closed_callback_ (remote_peer_, shared_from_this ());
562556 }
557+
558+ close_after_write_ = true ;
559+ if (reply_to_peer_code) {
560+ enqueue (goAwayMsg (*reply_to_peer_code));
561+ } else {
562+ write_queue_.clear ();
563+ std::ignore = connection_->close ();
564+ }
563565 }
564566
565567 void YamuxedConnection::writeStreamData (uint32_t stream_id, BytesIn data) {
@@ -634,6 +636,8 @@ namespace libp2p::connection {
634636 void YamuxedConnection::onDataWritten (outcome::result<size_t > res,
635637 StreamId stream_id) {
636638 if (!res) {
639+ write_queue_.clear ();
640+ std::ignore = connection_->close ();
637641 // write error
638642 close (res.error (), boost::none);
639643 return ;
@@ -672,10 +676,12 @@ namespace libp2p::connection {
672676
673677 is_writing_ = false ;
674678
675- if (started_ && ! write_queue_.empty ()) {
679+ if (not write_queue_.empty ()) {
676680 auto next_packet = std::move (write_queue_.front ());
677681 write_queue_.pop_front ();
678682 doWrite (std::move (next_packet));
683+ } else if (close_after_write_) {
684+ std::ignore = connection_->close ();
679685 }
680686 }
681687
0 commit comments