1+ #![ cfg( test) ]
2+ #![ allow( dead_code) ]
3+
4+ // ANCHOR: example
5+ use async_std:: { task, net:: TcpListener , net:: TcpStream } ;
6+ use futures:: AsyncWriteExt ;
7+
8+ async fn process_request ( stream : & mut TcpStream ) -> Result < ( ) , std:: io:: Error > {
9+ stream. write_all ( b"HTTP/1.1 200 OK\r \n \r \n " ) . await ?;
10+ stream. write_all ( b"Hello World" ) . await ?;
11+ Ok ( ( ) )
12+ }
13+
14+ async fn main ( ) {
15+ let listener = TcpListener :: bind ( "127.0.0.1:8080" ) . await . unwrap ( ) ;
16+ loop {
17+ // Accept a new connection
18+ let ( mut stream, _) = listener. accept ( ) . await . unwrap ( ) ;
19+ // Now process this request without blocking the main loop
20+ task:: spawn ( async move { process_request ( & mut stream) . await } ) ;
21+ }
22+ }
23+ // ANCHOR_END: example
24+ use std:: time:: Duration ;
25+ async fn my_task ( time : Duration ) {
26+ println ! ( "Hello from my_task with time {:?}" , time) ;
27+ task:: sleep ( time) . await ;
28+ println ! ( "Goodbye from my_task with time {:?}" , time) ;
29+ }
30+ // ANCHOR: join_all
31+ use futures:: future:: join_all;
32+ async fn task_spawner ( ) {
33+ let tasks = vec ! [
34+ task:: spawn( my_task( Duration :: from_secs( 1 ) ) ) ,
35+ task:: spawn( my_task( Duration :: from_secs( 2 ) ) ) ,
36+ task:: spawn( my_task( Duration :: from_secs( 3 ) ) ) ,
37+ ] ;
38+ // If we do not await these tasks and the function finishes, they will be dropped
39+ join_all ( tasks) . await ;
40+ }
41+ // ANCHOR_END: join_all
42+
43+ #[ test]
44+ fn run_task_spawner ( ) {
45+ futures:: executor:: block_on ( task_spawner ( ) ) ;
46+ }
0 commit comments