I don't see a better way to implement this until the whole 'how to do async properly?' question is solved.
Stopping a network server from accepting further connections
-
13-07-2023 - |
Pregunta
Currently I do this in order to stop a server from accepting further connections upon external request (e.g. a client sends "shutdown" message):
let listener = try_err!(TcpListener::bind(addr), "cannot bind: {}");
let (tstreams, rstreams) = channel();
let (tshutdown, rshutdown) = channel();
spawn(proc() {
let mut acceptor = try_err!(listener.listen(), "cannot listen: {}");
loop {
acceptor.set_timeout(Some(100));
match acceptor.accept() {
Ok(stream) => tstreams.send(stream),
Err(ref e) if e.kind == TimedOut => {}
Err(e) => println!("Failed to accept: {}", e)
}
match rshutdown.try_recv() {
Ok(()) | Err(Disconnected) => break,
Err(Empty) => {}
}
}
});
Then I can receive incoming connections through rstreams
channel and are able to shut down the acceptor loop via tshutdown
channel.
However, I dislike this approach, especially arbitrary Some(100)
timeout which seems to be inevitable here. Is it possible to do something better than this?
Solución
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow