use async_io::Async;
use blocking::{unblock, Unblock};
use futures_lite::prelude::*;
use std::cell::Cell;
use std::fs::File;
use std::net::TcpListener;
use unsend::channel::channel;
use unsend::executor::Executor;
fn main() {
async_io::block_on(async {
let (tx, rx) = channel();
let shared = Cell::new(1);
let executor = Executor::new();
executor
.spawn(async move {
let file = unblock(|| File::create("log.txt")).await.unwrap();
let mut file = Unblock::new(file);
while let Ok(msg) = rx.recv().await {
let message = format!("Sent out: {}\n", msg);
file.write_all(message.as_bytes()).await.unwrap();
}
})
.detach();
executor
.run(async {
loop {
let listener = Async::<TcpListener>::bind(([0, 0, 0, 0], 3000)).unwrap();
let (mut stream, _) = listener.accept().await.unwrap();
let tx = tx.clone();
let shared = &shared;
executor
.spawn(async move {
let mut buf = [0; 4];
stream.read_exact(&mut buf).await.unwrap();
let value = u32::from_be_bytes(buf);
let value = value * shared.get();
shared.set(shared.get() + 1);
stream.write_all(&value.to_be_bytes()).await.unwrap();
tx.send(value).unwrap();
})
.detach();
}
})
.await;
});
}