]> git.lizzy.rs Git - connect-rs.git/blob - src/tcp/client.rs
make async-oriented, remove block_on
[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>(
8         ip_addrs: A,
9     ) -> anyhow::Result<Self> {
10         let stream = TcpStream::connect(&ip_addrs).await?;
11         info!("Established client TCP connection to {}", ip_addrs);
12
13         stream.set_nodelay(true)?;
14         Ok(Self::from(stream))
15     }
16 }
17
18 impl From<TcpStream> for Connection {
19     fn from(stream: TcpStream) -> Self {
20         let write_stream = stream.clone();
21
22         let local_addr = stream
23             .local_addr()
24             .expect("Local address could not be retrieved");
25
26         let peer_addr = stream
27             .peer_addr()
28             .expect("Peer address could not be retrieved");
29
30         Self::new(
31             local_addr,
32             peer_addr,
33             Box::pin(stream),
34             Box::pin(write_stream),
35         )
36     }
37 }