我使用this code作为服务器,并修改了this tutorial作为客户端代码。当客户端连接到服务器时,它会永久阻止自己。
服务器
extern crate futures;
extern crate futures_io;
extern crate futures_mio;
use std::net::SocketAddr;
use futures::Future;
use futures_io::{copy, TaskIo};
use futures::stream::Stream;
fn main() {
let addr = "127.0.0.1:8080".parse::<SocketAddr>().unwrap();
let mut l = futures_mio::Loop::new().unwrap();
let server = l.handle().tcp_listen(&addr);
let done = server.and_then(move |socket| {
println!("Listening on: {}", addr);
socket.incoming().for_each(|(socket, addr)| {
let io = TaskIo::new(socket);
let pair = io.map(|io| io.split());
let amt = pair.and_then(|(reader, writer)| {
copy(reader, writer)
});
amt.map(move |amt| {
println!("wrote {} bytes to {}", amt, addr)
}).forget();
Ok(())
})
});
l.run(done).unwrap();
}
客户端:
extern crate futures;
extern crate futures_io;
extern crate futures_mio;
use std::net::SocketAddr;
use futures::Future;
use futures_mio::Loop;
fn main() {
let mut lp = Loop::new().unwrap();
let addr = "127.0.0.1:8080".parse::<SocketAddr>().unwrap();
let socket = lp.handle().tcp_connect(&addr);
let request = socket.and_then(|socket| {
futures_io::write_all(socket, b"Hello!")
});
let response = request.and_then(|(socket, _)| {
futures_io::read_to_end(socket, Vec::new())
});
let data = lp.run(response).unwrap();
println!("{}", String::from_utf8_lossy(&data));
}
答案 0 :(得分:8)
问题与期货无关。你有一个开放的插座,你要求直到结束时再读它#34; 决定结束的是什么?在这种情况下,套接字关闭时;那是什么时候?
欺骗问题!
那么什么时候发生?因为没有具体的代码,它会在套接字被删除时关闭,所以:
let response = request.and_then(|(socket, _)| {
socket.shutdown(std::net::Shutdown::Write).expect("Couldn't shut down");
read_to_end(socket, Vec::new())
});