AsyncClient

Struct AsyncClient 

Source
pub struct AsyncClient { /* private fields */ }
Expand description

Async tcp connection builder

async version of crate::tcp::Client, require tokio async runtime

Implementations§

Source§

impl Client

Source

pub fn new( server_addr: &str, id: &str, local_addr: Option<SocketAddr>, ) -> Result<Self>

set rendezvous server, peer identity, local bind address. if no local address set, choose according server address type(ipv4 or ipv6).

Examples found in repository?
examples/demo-async-tcp.rs (line 23)
12async fn main() -> Result<(), Box<dyn Error>> {
13    let server_addr = "127.0.0.1:8888";
14
15    {
16        let server_addr = server_addr.clone();
17        spawn(async move { Server::new(server_addr).await?.run().await });
18    }
19
20    let t = {
21        let server_addr = server_addr.clone();
22        spawn(async move {
23            let mut c = AsyncClient::new(server_addr, "c1", None).unwrap();
24            loop {
25                match c.listen().await {
26                    Ok(_) => {
27                        let (mut s, _) = c.accept().await.unwrap();
28                        s.write(b"hello").await.unwrap();
29                        break;
30                    }
31                    _ => {
32                        sleep(Duration::from_secs(1)).await;
33                        continue;
34                    }
35                }
36            }
37        })
38    };
39
40    let mut c = AsyncClient::new(server_addr, "c2", None)?;
41    let mut s = loop {
42        match c.connect("c1").await {
43            Ok(s) => break s,
44            _ => sleep(Duration::from_secs(1)).await,
45        }
46    };
47
48    let mut buf = [0u8; 5];
49    s.read(&mut buf).await?;
50
51    t.await?;
52
53    Ok(())
54}
Source

pub fn as_socket(&self) -> Option<&TcpListener>

expose TcpListener

Source

pub async fn connect(&mut self, target_id: &str) -> Result<TcpStream>

connect to rendezvous server and request a connection to target node.

it will return a TcpStream with remote peer.

the connection with rendezvous server will be drop after return.

Examples found in repository?
examples/demo-async-tcp.rs (line 42)
12async fn main() -> Result<(), Box<dyn Error>> {
13    let server_addr = "127.0.0.1:8888";
14
15    {
16        let server_addr = server_addr.clone();
17        spawn(async move { Server::new(server_addr).await?.run().await });
18    }
19
20    let t = {
21        let server_addr = server_addr.clone();
22        spawn(async move {
23            let mut c = AsyncClient::new(server_addr, "c1", None).unwrap();
24            loop {
25                match c.listen().await {
26                    Ok(_) => {
27                        let (mut s, _) = c.accept().await.unwrap();
28                        s.write(b"hello").await.unwrap();
29                        break;
30                    }
31                    _ => {
32                        sleep(Duration::from_secs(1)).await;
33                        continue;
34                    }
35                }
36            }
37        })
38    };
39
40    let mut c = AsyncClient::new(server_addr, "c2", None)?;
41    let mut s = loop {
42        match c.connect("c1").await {
43            Ok(s) => break s,
44            _ => sleep(Duration::from_secs(1)).await,
45        }
46    };
47
48    let mut buf = [0u8; 5];
49    s.read(&mut buf).await?;
50
51    t.await?;
52
53    Ok(())
54}
Source

pub async fn listen(&mut self) -> Result<()>

put socket in listen mode, create connection with rendezvous server, wait for peer connection request. if connection with server broken it will auto reconnect.

when received Fsync request from server, attempt to connect remote peer with a very short timeout, this will open the firwall and nat rule for the peer connection that will follow immediately. When the peer connection finally come, the listening socket then accept it as normal.

Examples found in repository?
examples/demo-async-tcp.rs (line 25)
12async fn main() -> Result<(), Box<dyn Error>> {
13    let server_addr = "127.0.0.1:8888";
14
15    {
16        let server_addr = server_addr.clone();
17        spawn(async move { Server::new(server_addr).await?.run().await });
18    }
19
20    let t = {
21        let server_addr = server_addr.clone();
22        spawn(async move {
23            let mut c = AsyncClient::new(server_addr, "c1", None).unwrap();
24            loop {
25                match c.listen().await {
26                    Ok(_) => {
27                        let (mut s, _) = c.accept().await.unwrap();
28                        s.write(b"hello").await.unwrap();
29                        break;
30                    }
31                    _ => {
32                        sleep(Duration::from_secs(1)).await;
33                        continue;
34                    }
35                }
36            }
37        })
38    };
39
40    let mut c = AsyncClient::new(server_addr, "c2", None)?;
41    let mut s = loop {
42        match c.connect("c1").await {
43            Ok(s) => break s,
44            _ => sleep(Duration::from_secs(1)).await,
45        }
46    };
47
48    let mut buf = [0u8; 5];
49    s.read(&mut buf).await?;
50
51    t.await?;
52
53    Ok(())
54}
Source

pub async fn accept(&mut self) -> Result<(TcpStream, SocketAddr)>

accept remote peer connection

Examples found in repository?
examples/demo-async-tcp.rs (line 27)
12async fn main() -> Result<(), Box<dyn Error>> {
13    let server_addr = "127.0.0.1:8888";
14
15    {
16        let server_addr = server_addr.clone();
17        spawn(async move { Server::new(server_addr).await?.run().await });
18    }
19
20    let t = {
21        let server_addr = server_addr.clone();
22        spawn(async move {
23            let mut c = AsyncClient::new(server_addr, "c1", None).unwrap();
24            loop {
25                match c.listen().await {
26                    Ok(_) => {
27                        let (mut s, _) = c.accept().await.unwrap();
28                        s.write(b"hello").await.unwrap();
29                        break;
30                    }
31                    _ => {
32                        sleep(Duration::from_secs(1)).await;
33                        continue;
34                    }
35                }
36            }
37        })
38    };
39
40    let mut c = AsyncClient::new(server_addr, "c2", None)?;
41    let mut s = loop {
42        match c.connect("c1").await {
43            Ok(s) => break s,
44            _ => sleep(Duration::from_secs(1)).await,
45        }
46    };
47
48    let mut buf = [0u8; 5];
49    s.read(&mut buf).await?;
50
51    t.await?;
52
53    Ok(())
54}

Trait Implementations§

Source§

impl Drop for Client

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl !Freeze for Client

§

impl RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl UnwindSafe for Client

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.