use tokio_global::{Runtime, AutoRuntime};
use tokio::io::{self, AsyncWriteExt, AsyncReadExt};
async fn server() {
let mut listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await.expect("To bind");
let (mut socket, _) = listener.accept().await.expect("To accept connection");
async move {
let mut buf = [0; 1024];
loop {
match socket.read(&mut buf).await {
Ok(0) => return,
Ok(_) => Runtime::stop(),
Err(_) => panic!("Error :("),
};
}
}.spawn().await.expect("Finish listening");
}
async fn do_stuff() -> Result<tokio::net::TcpStream, io::Error> {
tokio::net::TcpStream::connect("127.0.0.1:8081").await
}
async fn client() -> Result<(), io::Error> {
let mut stream = tokio::net::TcpStream::connect("127.0.0.1:8080").await.expect("Connect");
stream.write_all(b"hello world!").await
}
#[test]
fn run_global_runtime() {
let _runtime = Runtime::default();
let runner = std::thread::spawn(|| {
Runtime::run();
});
server().spawn();
assert!(do_stuff().wait().is_err());
assert!(client().wait().is_ok());
runner.join().expect("Finish running");
}