File tree Expand file tree Collapse file tree 2 files changed +72
-0
lines changed
Expand file tree Collapse file tree 2 files changed +72
-0
lines changed Original file line number Diff line number Diff line change @@ -49,6 +49,42 @@ fn main() {
4949}
5050```
5151
52+ ## Low-Friction Sockets with Built-In Timeouts
53+
54+ ``` rust
55+ #![feature(async_await)]
56+
57+ use std :: time :: Duration ;
58+
59+ use async_std :: {
60+ prelude :: * ,
61+ task,
62+ io,
63+ net :: TcpStream ,
64+ };
65+
66+ async fn get () -> io :: Result <Vec <u8 >> {
67+ let mut stream = TcpStream :: connect (" example.com:80" ). await ? ;
68+ stream . write_all (b " GET /index.html HTTP/1.0\ r\ n\ r\ n" ). await ? ;
69+
70+ let mut buf = vec! [];
71+
72+ io :: timeout (Duration :: from_secs (5 ), async {
73+ stream . read_to_end (& mut buf ). await ?
74+ Ok (buf )
75+ })
76+ }
77+
78+ fn main () {
79+ task :: block_on (async {
80+ let raw_response = get (). await . expect (" request" );
81+ let response = String :: from_utf8 (raw_response )
82+ . expect (" utf8 conversion" );
83+ println! (" received: {}" , response );
84+ });
85+ }
86+ ```
87+
5288## Take a look around
5389
5490Clone the repo:
Original file line number Diff line number Diff line change 2222//! })
2323//! }
2424//! ```
25+ //!
26+ //! Use sockets in a familiar way, with low-friction built-in timeouts:
27+ //!
28+ //! ```no_run
29+ //! #![feature(async_await)]
30+ //!
31+ //! use std::time::Duration;
32+ //!
33+ //! use async_std::{
34+ //! prelude::*,
35+ //! task,
36+ //! io,
37+ //! net::TcpStream,
38+ //! };
39+ //!
40+ //! async fn get() -> io::Result<Vec<u8>> {
41+ //! let mut stream = TcpStream::connect("example.com:80").await?;
42+ //! stream.write_all(b"GET /index.html HTTP/1.0\r\n\r\n").await?;
43+ //!
44+ //! let mut buf = vec![];
45+ //!
46+ //! io::timeout(Duration::from_secs(5), async {
47+ //! stream.read_to_end(&mut buf).await?
48+ //! Ok(buf)
49+ //! })
50+ //! }
51+ //!
52+ //! fn main() {
53+ //! task::block_on(async {
54+ //! let raw_response = get().await.expect("request");
55+ //! let response = String::from_utf8(raw_response)
56+ //! .expect("utf8 conversion");
57+ //! println!("received: {}", response);
58+ //! });
59+ //! }
60+ //! ```
2561
2662#![ feature( async_await) ]
2763#![ cfg_attr( feature = "docs" , feature( doc_cfg) ) ]
You can’t perform that action at this time.
0 commit comments