How to close tcp connection when using tokio

Hello,
I'm working on a tcp relay app and I find my server has a lot of FIN_WAIT2 connections, so I am wondering what is the right approach to safely close tcp connections

let mut remote_tcp = TcpStream::connect(addr()).await.unwrap();
let (mut reader, mut writer)= remote_tcp.into_split();
tokio::spawn( async move { do_something_with_reader(reader) } );
do_something_with_writer(writer);

As you seem to already understand, the FIN_WAIT_2 state on the server means the client is not closing its side of the connection. Closing TCP connections is sadly not documented by tokio, but you'll have to drop both the reader and writer halves of the TcpStream to close the underlying socket.

I'm not sure, but calling AsyncWriteExt::shutdown on just the writer half might also work in this situation though?

Edit: it looks like shutdown() is already called automatically by tokio when dropping the writer half, so that would be equivalent.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.