我正在尝试让这个简单的TCP服务器发送回“Hello!”信息。当它成功连接,并在发送消息时将消息输出到控制台,它不响应(stream.write()
)。
use std::str::from_utf8;
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};
fn main() {
let listener = TcpListener::bind("0.0.0.0", 8000);
let mut acceptor = listener.listen();
fn handle_client(mut stream: TcpStream) {
println!("Something's happening!");
let resp_bytes = bytes!("Hello!!");
let mut buf = [0u8, ..1024];
stream.read(buf);
stream.write(resp_bytes);
let req = from_utf8(buf);
println!("{}", req);
}
for stream in acceptor.incoming() {
match stream {
Err(e) => { println!("Something gone bad.") }
Ok(stream) => spawn(proc() {
handle_client(stream)
})
}
}
drop(acceptor);
}
如果我acceptor.incoming()
代替stream = acceptor.accept()
,然后执行stream.write()
,我可以让它工作。否则,我无法向客户发回消息。