socketsasynchronousrustrust-tokiotcplistener

Can I convert from socket2::Socket to Tokio::net::TcpStream?


I would like to use tokio::net::TcpStream as an asynchronous TCP listener. On the other hand, I also want to use set_reuse_address, set_reuse_port, and set_nonblocking in socket2::Socket.

How can I convert from socket2::Socket to tokio::net::TcpStream?

I would like to use tokio::net:TcpStream to listen for efficient and non-blocking TCP connections using asynchronous callbacks.

If you find that such a thing is not possible in the first place or that my understanding of asynchronous is incorrect, I would be grateful if you could point out anything. thank you.


Solution

  • Yes, you can convert both from/to std::net::TcpStream so you can go through that as common exchange format.

    use tokio::net::TcpStream;
    use socket2::Socket;
    fn socket_to_async_stream(s: Socket) -> std::io::Result<TcpStream> {
        std::net::TcpStream::from(s).try_into()
    }
    fn async_stream_to_socket(t: TcpStream) -> std::io::Result<Socket> {
        t.into_std().map(Into::into)
    }