Idiomatic way to get from a socket2 Socket to a Tokio TcpStream

Hi all,

I’ve been playing with socket2 and whilst it has the ability to go from that to a standard TcpStream ( via into() ), I need it was the Tokio variant.

I was wondering what is the best to do this sort of double conversion. Or if there is a better way that I’m completely missing (very likely I feel :sweat_smile:)


It looks like you can convert from a std TcpStream to a tokio TcpStream with TcpStream::from_std

I was just coming back to say that I had found that and it seems to be working fine. I feel more confident in that choice now that you’ve highlighted it too :grin:

It didn’t show up in my original more naive search so hopefully this question will be easier to find for others like me in the future.

Thanks for your help, greatly appreciated!

1 Like

Ah, actually I ended up converting the socket2 SockAddr to Tokio’s TcpSocket. When you call connect on that, it returns a TcpStream.

I originally tried converting between the streams but the connect function in socket2, while being non blocking, doesn’t use Tokio to manage it, so I started looking deeper.

That’s when I found TcpSocket::from_std_stream(). With that I can set up why I need and then use connect on TcpSocket which uses Tokio directly :relaxed:

1 Like

If you create the socket using socket2, then going through std is the solution. Remember to set the non-blocking flag!

It's also possible to create it with Tokio, then modify it via socket2 using the SockRef type.

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.