javadetectionzeroconfjmdns

JmDNS device removal detection


I am trying to use JmDNS to detect addition and removal of devices on the network. The addition works fine, the devices are found as soon as their respective services are registered with JmDNS, but, when a device is removed from the network, it is never registered with JmDNS.

I have tried invoking jmDns.list(serviceName) periodically, but, it seems, as if it always returns cached values.

Is it possible to make JmDNS register removed devices?

Here is the code I used to register service and service listener (only relevant parts):

Service:

JmDNS jmdns = JmDNS.create();
ServiceInfo service = ServiceInfo.create("_test._tcp.local.", "Test", 1234, 0, 0, false, "Test info");
jmdns.registerService(service);

Service listener:

JmDNS jmDns = JmDNS.create();
jmDns.addServiceListener("_test._tcp.local.", new ServiceListener() {
    @Override
    public void serviceAdded(ServiceEvent event) {
        System.out.println("Service added " + event.getInfo());
    }

    @Override
    public void serviceRemoved(ServiceEvent event) {
        System.out.println("Service removed " + event.getInfo());
    }

    @Override
    public void serviceResolved(ServiceEvent event) {
        System.out.println("Service resolved" + event.getInfo());
    }
});

Method serviceRemoved() is never invoked, even though the device previously registered is not powered on anymore. I am very grateful for any help I can get in solving the issue.

Update: JmDNS does figure out that the device is missing from the network, but only after half an hour. Is it possible to make this period shorter?


Solution

  • The serviceRemoved() method is only called when the removed device unregisters itself before shutting down. JmDNS is not actively checking the presence of the devices but just listening to the broadcast messages. If the removed device has not unregistered itself JmDNS does never know it util the timeout hits in (probably 30minutes in your case). One possibility to check if a device is still there is to actively ask it. There are several ways to do this. I dont know if JmDNS has already something build if for that.