Skip to content

Instantly share code, notes, and snippets.

@frol
Created January 7, 2019 21:33
Show Gist options
  • Select an option

  • Save frol/2159f75b46214bd24296e2285b0e6d28 to your computer and use it in GitHub Desktop.

Select an option

Save frol/2159f75b46214bd24296e2285b0e6d28 to your computer and use it in GitHub Desktop.
#![feature(async_await, await_macro, futures_api)]
use futures::task::SpawnExt;
use futures::io::{AsyncReadExt, AsyncWriteExt, AllowStdIo};
use romio::TcpStream;
async fn send_and_receive_request(id: i32) {
eprintln!("BEGIN send_and_receive_request #{}", id);
let stream = await!(TcpStream::connect(&"104.18.35.57:80".parse().unwrap())).unwrap();
let mut stdout = AllowStdIo::new(std::io::stdout());
let (mut reader, mut writer) = stream.split();
await!(writer.write_all(b"GET / HTTP/1.0\nHost: ifconfig.co\nUser-Agent: curl\n\n")).unwrap();
await!(reader.copy_into(&mut stdout)).unwrap();
eprintln!("END send_and_receive_request #{}", id);
}
fn main() {
eprintln!("BEGIN main");
let mut executor = futures::executor::ThreadPool::new().unwrap();
let mut executor_clone = executor.clone();
eprintln!("BEFORE running tasks");
executor.run(async {
eprintln!("BEGIN run_until");
eprintln!("BEGIN sending the request #1");
let request_1 = executor_clone.spawn_with_handle(send_and_receive_request(1)).unwrap();
eprintln!("BEGIN sending the request #2");
let request_2 = executor_clone.spawn_with_handle(send_and_receive_request(2)).unwrap();
eprintln!("AWAITING the request #2");
await!(request_2);
eprintln!("AWAITING the request #1");
await!(request_1);
eprintln!("END run_until");
});
eprintln!("END main");
}
@frol
Copy link
Author

frol commented Jan 7, 2019

Possible output:

BEGIN main
BEFORE running tasks
BEGIN run_until
BEGIN sending the request #1
BEGIN sending the request #2
AWAITING the request #2
BEGIN send_and_receive_request #1
BEGIN send_and_receive_request #2
HTTP/1.1 200 OK
Date: Mon, 07 Jan 2019 21:44:34 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 13
Connection: close
Set-Cookie: __cfduid=d30c3fb7b11f0db31541c212aeaf49de11546897474; expires=Tue, 07-Jan-20 21:44:34 GMT; path=/; domain=.ifconfig.co; HttpOnly
Via: 1.1 vegur
Server: cloudflare
CF-RAY: 49599b4024c58b94-KBP

176.100.2.43
END send_and_receive_request #1
HTTP/1.1 200 OK
Date: Mon, 07 Jan 2019 21:44:34 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 13
Connection: close
Set-Cookie: __cfduid=d30c3fb7b11f0db31541c212aeaf49de11546897474; expires=Tue, 07-Jan-20 21:44:34 GMT; path=/; domain=.ifconfig.co; HttpOnly
Via: 1.1 vegur
Server: cloudflare
CF-RAY: 49599b4024c48b94-KBP

176.100.2.43
END send_and_receive_request #2
AWAITING the request #1
END run_until
END main

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment