windy1 / zeroconf-rs

zeroconf is a cross-platform library that wraps underlying ZeroConf/mDNS implementations such as Bonjour or Avahi, providing an easy and idiomatic way to both register and browse services.
MIT License
77 stars 25 forks source link

Resolving the eventloop.poll() #8

Closed Frantisekf closed 3 years ago

Frantisekf commented 3 years ago

Hi, I'm very very new to rust and MDNS stuff so I apologize for dumb questions. I stumbled upon this problem with service browsers, and that's how to actually break the poll loop and return the found services back to main method. the code is similar to the example for browsing

fn on_service_discovered(
    result: zeroconf::Result<ServiceDiscovery>,
    _context: Option<Arc<dyn Any>>,
) {
    let res = result.unwrap();

    let serialized = serde_json::to_string(&res).unwrap();
    println!("serialized = {}", serialized);
}

#[tokio::main]
async fn main() {
    // let services = RwLock::new(Vec::new());
    // listen(services.write()?);

    let mut browser = MdnsBrowser::new("_http._tcp");

    browser.set_service_discovered_callback(Box::new(on_service_discovered));    
    let event_loop = browser.browse_services().unwrap();

    loop {    
        event_loop.poll(Duration::from_secs(0)).result();
     }
windy1 commented 3 years ago

It really depends on the design of your application but one way to do this would have a bool field in your context object and check that in the loop. The context could be updated in another thread or something when you want to shutdown.

Example