]> git.lizzy.rs Git - connect-rs.git/blob - src/tcp/client.rs
avoid block_on as much as possible
[connect-rs.git] / src / tcp / client.rs
1 use log::*;
2
3 use crate::Connection;
4 use async_std::net::{TcpStream, ToSocketAddrs};
5
6 impl Connection {
7     pub async fn tcp_client<A: ToSocketAddrs + std::fmt::Display>(ip_addrs: A) -> anyhow::Result<Self> {
8         let stream = TcpStream::connect(&ip_addrs).await?;
9         info!("Established client TCP connection to {}", ip_addrs);
10
11         stream.set_nodelay(true)?;
12         Ok(Self::from(stream))
13     }
14 }
15
16 impl From<TcpStream> for Connection {
17     fn from(stream: TcpStream) -> Self {
18         let write_stream = stream.clone();
19
20         let local_addr = stream
21             .local_addr()
22             .expect("Local address could not be retrieved");
23
24         let peer_addr = stream
25             .peer_addr()
26             .expect("Peer address could not be retrieved");
27
28         Self::new(
29             local_addr,
30             peer_addr,
31             Box::pin(stream),
32             Box::pin(write_stream),
33         )
34     }
35 }