Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 15, 2019 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/08bc3e0c6268d447b4d041f19d903131 to your computer and use it in GitHub Desktop.
Save rust-play/08bc3e0c6268d447b4d041f19d903131 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![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