]> git.lizzy.rs Git - connect-rs.git/blob - src/tcp/client.rs
renamed server to listener and add thorough documentation
[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     /// Creates a [`Connection`] that uses a TCP transport
8     ///
9     /// # Example
10     ///
11     /// Basic usage:
12     ///
13     /// ```ignore
14     /// let mut conn = Connection::tcp_client("127.0.0.1:3456").await?;
15     /// ```
16     pub async fn tcp_client<A: ToSocketAddrs + std::fmt::Display>(
17         ip_addrs: A,
18     ) -> anyhow::Result<Self> {
19         let stream = TcpStream::connect(&ip_addrs).await?;
20         info!("Established client TCP connection to {}", ip_addrs);
21
22         stream.set_nodelay(true)?;
23         Ok(Self::from(stream))
24     }
25 }
26
27 impl From<TcpStream> for Connection {
28     /// Creates a [`Connection`] using a TCP transport from an async [`TcpStream`].
29     fn from(stream: TcpStream) -> Self {
30         let write_stream = stream.clone();
31
32         let local_addr = stream
33             .local_addr()
34             .expect("Local address could not be retrieved");
35
36         let peer_addr = stream
37             .peer_addr()
38             .expect("Peer address could not be retrieved");
39
40         Self::new(
41             local_addr,
42             peer_addr,
43             Box::pin(stream),
44             Box::pin(write_stream),
45         )
46     }
47 }