Use non-blocking io in example
This commit is contained in:
parent
4680542d2d
commit
be7c684367
|
@ -9,5 +9,3 @@ edition = "2021"
|
|||
|
||||
[dev-dependencies]
|
||||
foxtrot = { git = "https://git.asonix.dog/safe-async/foxtrot" }
|
||||
# async-io = "1.6.0"
|
||||
# futures-lite = "1.12.0"
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
use foxtrot::Async;
|
||||
use foxtrot::{
|
||||
io::{Nonblocking, ReadBytes, Readiness},
|
||||
Async,
|
||||
};
|
||||
use jitterbug::Executor;
|
||||
use std::time::Duration;
|
||||
|
||||
|
@ -32,27 +35,55 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
execu2r.spawn(async move {
|
||||
println!("Accepted stream");
|
||||
|
||||
let mut buffer = [0; 1024];
|
||||
let mut bytes = vec![];
|
||||
let mut buf = [0; 1024];
|
||||
let mut interests = Readiness::read();
|
||||
|
||||
while let Ok(n) = stream.read(&mut buffer).await {
|
||||
if n == 0 {
|
||||
'l2: loop {
|
||||
let readiness = stream.ready(interests).await?;
|
||||
|
||||
if readiness.is_hangup() {
|
||||
break;
|
||||
}
|
||||
|
||||
if let Ok(s) = std::str::from_utf8(&buffer[0..n]) {
|
||||
let mut string = s.trim().chars().rev().collect::<String>();
|
||||
println!("{:?}: {}", std::thread::current().id(), string);
|
||||
string.push('\n');
|
||||
|
||||
if stream.write_all(string.as_bytes()).await.is_err() {
|
||||
break;
|
||||
if readiness.is_read() {
|
||||
loop {
|
||||
match stream.read_nonblocking(&mut buf)? {
|
||||
Nonblocking::Ready(ReadBytes::Read(n)) => {
|
||||
let n: usize = n.into();
|
||||
bytes.extend_from_slice(&buf[0..n]);
|
||||
if n < buf.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Nonblocking::Ready(ReadBytes::EOF) if bytes.is_empty() => break 'l2,
|
||||
Nonblocking::Ready(ReadBytes::EOF) | Nonblocking::WouldBlock => {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !bytes.is_empty() {
|
||||
interests = Readiness::read() | Readiness::write();
|
||||
}
|
||||
}
|
||||
|
||||
if readiness.is_write() {
|
||||
match stream.write_nonblocking(&bytes)? {
|
||||
Nonblocking::Ready(n) => {
|
||||
bytes = bytes.split_off(n);
|
||||
if bytes.is_empty() {
|
||||
interests = Readiness::read();
|
||||
}
|
||||
}
|
||||
Nonblocking::WouldBlock => {}
|
||||
}
|
||||
} else if stream.write_all(&buffer[0..n]).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
println!("Stream closed");
|
||||
|
||||
Ok(()) as foxtrot::io::Result<()>
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue