Created
July 3, 2020 21:06
-
-
Save narodnik/7c50abc51326a259ae8375e726799a55 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::net::TcpStream; | |
use futures::io; | |
use futures::prelude::*; | |
use smol::{Async, Timer}; | |
use std::time::Duration; | |
async fn sleep(seconds: u64) { | |
Timer::after(Duration::from_secs(seconds)).await; | |
} | |
async fn try_connect() -> Async::<TcpStream> { | |
loop { | |
for i in 0..3u32 { | |
match Async::<TcpStream>::connect("127.0.0.1:7000").await { | |
Ok(stream) => return stream, | |
Err(_) => { | |
println!("Failed to connect, attempt #{}", i); | |
sleep(1).await; | |
} | |
} | |
} | |
println!("Reconnecting in 60 seconds..."); | |
sleep(10).await; | |
} | |
} | |
fn main() -> io::Result<()> { | |
smol::run(async { | |
// Create async stdin and stdout handles. | |
let mut stdin = smol::reader(std::io::stdin()); | |
let mut stdout = smol::writer(std::io::stdout()); | |
// Connect to the server. | |
let mut stream = try_connect().await; | |
println!("Connected to {}", stream.get_ref().peer_addr()?); | |
println!("Type a message and hit enter!\n"); | |
// Pipe messages from stdin to the server and pipe messages from the server to stdout. | |
let mut data = vec![0u8; 10]; | |
stdin.read_exact(&mut data[..10]).await?; | |
stream.write_all(&data).await?; | |
stream.read_exact(&mut data).await?; | |
stdout.write_all(&data).await?; | |
stdout.flush().await?; | |
stdout.close().await?; | |
//future::try_join( | |
// io::copy(stdin, &mut &stream), | |
// io::copy(&stream, &mut stdout), | |
//) | |
//.await?; | |
Ok(()) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment