1
我想寫一個TCP客戶端來打印傳入的消息。我想出了下面的代碼:如何在不使用tokio_proto箱子的情況下從tokio TCP連接讀取數據?
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;
use futures::Future;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_io::AsyncRead;
use bytes::BytesMut;
fn main() {
let mut core = Core::new().unwrap();
let handle = core.handle();
let connection = TcpStream::connect(&"127.0.0.1:8081".parse().unwrap(), &handle);
let server = connection.and_then(move |mut stream| {
let mut buf = BytesMut::with_capacity(1000);
stream
.read_buf(&mut buf)
.map(|buf| print!("Buffer {:?}", buf))
.map_err(|e| eprintln!("Error: {}", e));
Ok(())
});
core.run(server).unwrap();
}
它編譯,但它無法用Buffer NotReady
錯誤。
爲什麼如果你想運行一個服務器使用'TcpStream :: connect'? – Shepmaster
@Shepmaster現在我正在嘗試讀取任何東西。這樣更方便 - 我只是用'ncat'運行監聽器。我認爲閱讀套接字應該類似於服務器和客戶端。 – Sergey