Reputation: 11
Looking at the rust bible, there is the following code:
use std::net::TcpListener;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
println!("Connection established!");
}
}
I was wondering why the for loop doesn't exit. After one iteration of the for loop (ie. if nobody connects), shouldn't the for loop finish and the main function exit?
Upvotes: 2
Views: 486
Reputation: 60177
This is intended. From the documentation for TcpListener
regarding incoming()
notes:
The returned iterator will never return
None
and will also not yield the peer'sSocketAddr
structure. Iterating over it is equivalent to callingaccept
in a loop.
And accept()
notes:
This function will block the calling thread until a new TCP connection is established.
So it is designed to infinitely wait for connections and doesn't yield execution until one does.
You can change this behavior by calling listener.set_nonblocking(true)
to have accept
(and therefore the incoming
iterator) to immediately yield with the error io::ErrorKind::WouldBlock
if no connections are pending.
Upvotes: 5