]> git.lizzy.rs Git - connect-rs.git/blob - src/tcp/client.rs
remove `block_on` in tls-listener
[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     /// Please see the [tcp-client](https://github.com/sachanganesh/connect-rs/blob/main/examples/tcp-client/src/main.rs)
12     /// example program for a more thorough showcase.
13     ///
14     /// Basic usage:
15     ///
16     /// ```ignore
17     /// let mut conn = Connection::tcp_client("127.0.0.1:3456").await?;
18     /// ```
19     pub async fn tcp_client<A: ToSocketAddrs + std::fmt::Display>(
20         ip_addrs: A,
21     ) -> anyhow::Result<Self> {
22         let stream = TcpStream::connect(&ip_addrs).await?;
23         info!("Established client TCP connection to {}", ip_addrs);
24
25         stream.set_nodelay(true)?;
26         Ok(Self::from(stream))
27     }
28 }
29
30 impl From<TcpStream> for Connection {
31     /// Creates a [`Connection`] using a TCP transport from an async [`TcpStream`].
32     fn from(stream: TcpStream) -> Self {
33         let write_stream = stream.clone();
34
35         let local_addr = stream
36             .local_addr()
37             .expect("Local address could not be retrieved");
38
39         let peer_addr = stream
40             .peer_addr()
41             .expect("Peer address could not be retrieved");
42
43         Self::new(
44             local_addr,
45             peer_addr,
46             Box::pin(stream),
47             Box::pin(write_stream),
48         )
49     }
50 }