File: socket-timeouts.rs

package info (click to toggle)
rust-async-std 1.13.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,992 kB
  • sloc: sh: 13; makefile: 8
file content (28 lines) | stat: -rw-r--r-- 752 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//! Prints response of GET request made to TCP server with 5 second socket timeout

use std::time::Duration;

use async_std::{io, net::TcpStream, prelude::*, task};

async fn get() -> io::Result<Vec<u8>> {
    let mut stream = TcpStream::connect("example.com:80").await?;
    stream
        .write_all(b"GET /index.html HTTP/1.0\r\n\r\n")
        .await?;

    let mut buf = vec![];

    io::timeout(Duration::from_secs(5), async move {
        stream.read_to_end(&mut buf).await?;
        Ok(buf)
    })
    .await
}

fn main() {
    task::block_on(async {
        let raw_response = get().await.expect("request");
        let response = String::from_utf8(raw_response).expect("utf8 conversion");
        println!("received: {}", response);
    });
}