为什么在背对背println和print语句之间会有停顿?

时间:2018-12-06 22:44:17

标签: rust

我正在使用标准库net模块编写一个简单的HTTP请求:

use std::io::prelude::*;
use std::net;

fn main() -> std::io::Result<()> {
    let request = 
b"GET / HTTP/1.1
Host: localhost:8080

";

    let mut response = String::new();

    print!("Connecting...");
    let mut stream = net::TcpStream::connect("127.0.0.1:8080")
        .expect("Cannot connect to server");
    println!("Connected!");

    print!("Writing...");
    stream.write(request)
        .expect("Error writing");
    println!("Written!");

    print!("Reading...");
    stream.read_to_string(&mut response)
        .expect("Error reading");
    println!("Read!");

    println!("\nResponse:\n{}", response);
    Ok(())
}

我有一个简单的Express网络服务器,在localhost:8080上本地运行。

const express = require('express')
const app = express()
const port = 8080

app.get('/', (req, res) => {
  console.time('/')
  res.send('ok')
  console.timeEnd('/')
})

app.listen(port, () => console.log(`Server on ${port}`))

运行程序时,在Written!Reading...的打印之间会停一两秒钟。当似乎没有什么可以暂停执行时,为什么会出现该暂停?

服务器输出:

/: 5.168ms

铁锈输出:

Connecting...Connected!
Writing...Written! // PAUSES HERE AT EOL!
Reading...Read!

Response:
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 2
ETag: W/"2-eoX0dku9ba8cNUXvu/DyeabcC+s"
Date: Thu, 06 Dec 2018 22:32:47 GMT
Connection: keep-alive

ok

1 个答案:

答案 0 :(得分:3)

stdout通常是行缓冲的,这意味着它将您写入的内容存储在缓冲区中,直到看到换行符为止。因此,在println!("Read!");打印换行符之前,您什么都看不到。

如果要在此之前显示内容,则需要flush the buffer

use std::io;  // for io::stdout

...

print!("Reading...");
io::stdout().flush()?;