advance/async/web-server #836
Replies: 5 comments 11 replies
-
为什么我把依赖加上后总是build失败😥😥😥 |
Beta Was this translation helpful? Give feedback.
-
使用多线程并行处理请求: 同时发起多个 /sleep 请求, 第一个5s后返回,第二个 10s后返回,第三个15s后返回, 貌似并没有与多个线程同时处理这些请求吧? |
Beta Was this translation helpful? Give feedback.
-
单线程异步确实神奇 |
Beta Was this translation helpful? Give feedback.
-
多线程+async,
这不是为每个async开了个线程吗,那async还有什么意义?我的理解是async类似协程,把当前线程分成一个个task,可在task间无缝切换,但task阻塞则线程阻塞。但如果每个线程里只有一个async,不等于没async吗? |
Beta Was this translation helpful? Give feedback.
-
tokio 版本: use futures::stream::StreamExt;
use tokio::fs;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; // Use tokio::io::BufReader, AsyncBufReadExt, and AsyncWriteExt
use tokio::net::{TcpListener, TcpStream};
use tokio_stream::wrappers::TcpListenerStream;
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("127.0.0.1:8878").await.unwrap();
TcpListenerStream::new(listener)
.for_each_concurrent(None, |stream_result| async {
match stream_result {
Ok(stream) => {
handle_connection(stream).await;
}
Err(e) => eprintln!("Connection error: {}", e),
}
})
.await;
}
async fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&mut stream);
let mut lines = buf_reader.lines();
let request_line = lines.next_line().await.unwrap().unwrap();
let (status_line, filename) = if request_line == "GET / HTTP/1.1" {
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
let contents = fs::read_to_string(filename).await.unwrap();
let length = contents.len();
let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
stream.write_all(response.as_bytes()).await.unwrap();
} cargo.toml [package]
name = "hello"
version = "0.1.0"
edition = "2024"
[dependencies]
futures = "0.3"
tokio = { version = "1", features = ["full"] }
tokio-stream = { version = "0.1", features = ["net"] }
|
Beta Was this translation helpful? Give feedback.
-
advance/async/web-server
https://course.rs/advance/async/web-server.html
Beta Was this translation helpful? Give feedback.
All reactions