Created
September 15, 2019 10:36
-
-
Save rust-play/f65e040d6474d1a537247b1053c77601 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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
#![allow(unused_imports)] | |
use futures::stream::iter_ok; | |
use std::error::Error; | |
use std::ops::Add; | |
use std::sync::Arc; | |
use std::thread::sleep; | |
use std::time::Duration; | |
use tokio::io::{lines, read, read_exact, shutdown, write_all}; | |
use tokio::net::TcpStream; | |
use tokio::prelude::*; | |
fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> { | |
let ip_list = vec!["127.0.0.1:4028", "127.0.0.1:4029"]; | |
tokio::run(iter_ok(ip_list).for_each(|ip| { | |
println!("addr: {}", ip); | |
query_api(ip.to_string()) | |
})); | |
loop { | |
sleep(Duration::from_secs(1)); | |
} | |
} | |
fn query_api(addr: String) -> impl Future<Item = (), Error = ()> { | |
let stream = TcpStream::connect(&addr.parse().unwrap()); | |
stream | |
.and_then(|stream| { | |
stream.set_nodelay(true).unwrap(); | |
println!("connect: {:?}", &stream.peer_addr()); | |
Ok(stream) | |
}) | |
.and_then(|stream| write_all(stream, b"{\"command\":\"stats\"}")) | |
.and_then(|(stream, _body)| { | |
println!("send command: {:?}", _body); | |
Ok(stream) | |
}) | |
.and_then(|stream| { | |
let buf_stream = std::io::BufReader::new(stream); | |
let recv = vec![]; | |
lines(buf_stream).fold(recv, |mut recv, line| { | |
println!("line: {:?}b", &line.len()); | |
recv.push(line); | |
future::ok(recv) | |
}) | |
}) | |
.and_then(|recv| { | |
Ok(()) | |
}) | |
.map_err(|e| println!("error: {}", e)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment