Why can't it run non-blocking #4926
Answered
by
Darksonn
1148118271
asked this question in
Q&A
-
The following code does not run non-blocking, is there something wrong with my implementation? use std::io::ErrorKind;
use tokio::io::AsyncReadExt;
use tokio::net::{TcpListener, TcpStream};
#[tokio::main]
async fn main() {
server_run().await;
}
async fn server_run() {
let std_listener = std::net::TcpListener::bind("0.0.0.0:9258").unwrap();
std_listener.set_nonblocking(true).unwrap();
let listener = TcpListener::from_std(std_listener).unwrap();
loop {
let (server, addr) = listener.accept().await.unwrap();
println!("client addr {}", addr);
handle_client(server).await;
}
}
async fn handle_client(mut server: TcpStream) {
let mut msg_buf: Vec<u8> = vec![];
let mut buf = [0u8;512];
loop {
match server.read(&mut buf).await {
Ok(size) => {
println!("size {}", size);
if size == 0 {
println!("client disconnects.");
break;
}
msg_buf.extend_from_slice(&buf[..size]);
}
Err(e) => {
println!("e => {}", e);
if e.kind() == ErrorKind::WouldBlock {
println!("data read complete.");
break;
}
panic!("{}", e);
}
}
}
println!("{}", String::from_utf8(msg_buf).unwrap());
} |
Beta Was this translation helpful? Give feedback.
Answered by
Darksonn
Aug 19, 2022
Replies: 1 comment 1 reply
-
You didn't explain what the problem is, but maybe you're looking for this:
|
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
hawkw
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You didn't explain what the problem is, but maybe you're looking for this: