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