Skip to content

How can I tell whether the server is ready and open a web browser then? How do I find out if the server couldn't start because the port was busy? #751

Answered by ilyagr
ilyagr asked this question in Q&A
Discussion options

You must be logged in to vote

I have a theory of how to do this, based on the difference between an "Acceptor" and a "Listener". I'm not sure whether it's correct. I'll experiment if I don't hear from anybody.

Here's the outline I'm thinking about.

let mut port = 8000;
let acceptor = loop {
  if port > max_port {
    panic!();
  }
  // This seems like it never fails, unlike
  // https://doc.rust-lang.org/nightly/std/net/struct.TcpListener.html#method.bind
  let listener = TcpListener::bind(format!("127.0.0.1:{port}");
  match listener.into_acceptor() {
     Some(a) => return a,
     Err(_) => { port += 1} // Could also check the ErrorKind of this error, perhaps?
  }
}

println!("Server is ready for incoming connection…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@sunli829
Comment options

@sunli829
Comment options

@ilyagr
Comment options

@ilyagr
Comment options

Answer selected by ilyagr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants