69 lines
2.6 KiB
Rust
69 lines
2.6 KiB
Rust
use bachata::Executor;
|
|
use foxtrot::{
|
|
io::{Async, Nonblocking, Readiness},
|
|
net::TcpListener,
|
|
};
|
|
use read_write_buf::ReadWriteBuf;
|
|
|
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|
foxtrot::block_on(Executor::new().run_with(async move {
|
|
let executor = Executor::current();
|
|
let mut listener = Async::<TcpListener>::bind(([0, 0, 0, 0], 3456)).await?;
|
|
|
|
println!("Listening on port 3456");
|
|
|
|
loop {
|
|
let (mut stream, _) = listener.accept().await?;
|
|
|
|
executor.spawn(async move {
|
|
println!("Accepted stream");
|
|
|
|
let mut ring_buf = ReadWriteBuf::<10>::new();
|
|
let mut interests = Readiness::read();
|
|
|
|
loop {
|
|
let readiness = stream.ready(interests).await?;
|
|
|
|
if readiness.is_hangup() {
|
|
return Ok(()) as std::io::Result<()>;
|
|
}
|
|
|
|
if readiness.is_read() {
|
|
while let Some(buf) = ring_buf.for_reading() {
|
|
match stream.read_nonblocking(buf)? {
|
|
Nonblocking::Ready(n) if n > 0 => {
|
|
let should_break = n < buf.len();
|
|
ring_buf.advance_read(n);
|
|
if should_break {
|
|
break;
|
|
}
|
|
}
|
|
Nonblocking::Ready(_) if ring_buf.is_empty() => return Ok(()),
|
|
Nonblocking::Ready(_) | Nonblocking::WouldBlock => break,
|
|
}
|
|
}
|
|
|
|
if !ring_buf.is_empty() {
|
|
interests = Readiness::read() | Readiness::write();
|
|
}
|
|
}
|
|
|
|
if readiness.is_write() {
|
|
while let Some(buf) = ring_buf.for_writing() {
|
|
match stream.write_nonblocking(buf)? {
|
|
Nonblocking::Ready(n) => {
|
|
ring_buf.advance_write(n);
|
|
if ring_buf.is_empty() {
|
|
interests = Readiness::read();
|
|
}
|
|
}
|
|
Nonblocking::WouldBlock => break,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}))?
|
|
}
|