async-std
async-std copied to clipboard
Provide a way to configure sockets
Consider providing additional methods to configure socket
- SO_REUSEADDR
- SO_LINGER
I refrain from using async-std due to their absence. You can check these options in socket2 crate.
@Deniskore you can convert from socket2 types to std types, and in turn we provide conversions from std types to async_std types. async_std will ensure the non blocking flags are set correctly when converting.
I agree I'd love to see BSD socket support as part of std/async_std in the long term, but at least this should help get you unblocked!
@yoshuawuyts Could you please provide a code snippet for these conversions?
let socket = socket2::Socket::new(
socket2::Domain::ipv4(),
socket2::Type::stream(),
Some(socket2::Protocol::tcp()),
)?;
socket.set_reuse_address(true)?;
socket.set_linger(Some(Duration::from_secs(0)))?;
socket.bind(&"0.0.0.0:0".parse::<SocketAddr>()?.into())?;
// Convert and setup...
@Deniskore the following APIs are relevant here (for e.g. a TcpListener):
- https://docs.rs/socket2/0.3.11/socket2/struct.Socket.html#method.into_tcp_listener
- https://docs.rs/async-std/1.4.0/async_std/net/struct.TcpListener.html#impl-From%3CTcpListener%3E
Example
I haven't run the code, but this should get the general idea across:
let socket = socket2::Socket::new(
socket2::Domain::ipv4(),
socket2::Type::stream(),
Some(socket2::Protocol::tcp()),
)?;
socket.set_reuse_address(true)?;
socket.set_linger(Some(Duration::from_secs(0)))?;
let socket = socket.into_tcp_listener();
let socket: async_std::net::TcpListener = socket.into();
socket.bind("0.0.0.0").await?;
@yoshuawuyts But what if i need TcpStream? async-std has only static connect function. Tokio has tokio::net::TcpStream::from_std() for this purpose.
socket.set_reuse_address(true)?;
socket.set_linger(Some(Duration::from_secs(0)))?;
socket.bind(&"0.0.0.0:0".parse::<SocketAddr>()?.into())?;
let socket = socket.into_tcp_stream();
let stream: async_std::net::TcpStream = socket.into();
// ??
@Deniskore we provide From conversions for all std types. This includes TcpStream, so the example you wrote would indeed be the intended way to go about it.
Tangential question: what happens if I transform a TcpSocket into a TcpStream or TcpListener without having called connect or accept?