1

我创建了 JmDNS 示例:

public class Service {
public static void main(String[] args) {
    try {
        JmDNS mdnsServer = null;

        mdnsServer = JmDNS.create("localhost");

        // Register a test service.
        ServiceInfo testService = ServiceInfo.create("_myTest._tcp.local.", "Test-Service", 3, "test_service");
        mdnsServer.registerService(testService);
    } catch (IOException e) {
        e.printStackTrace();  
    }

}

}

它运行几秒钟然后退出程序,所以我想知道它是阻塞还是非阻塞。我在想,因为它通过网络广播服务,所以我们需要手动退出应用程序

跟随也是如此ServiceDiscovery

public class ServiceDiscovery {
private static ServiceListenerClass listener;
private static int count = 0;

public static void main(String[] args) throws IOException {
    JmDNS jmdns = null;
    InetAddress address = null;
    String type = "_myTest._tcp.local.";
        Enumeration<NetworkInterface> ifc = NetworkInterface.getNetworkInterfaces();
        while (ifc.hasMoreElements()) {
            NetworkInterface anInterface = ifc.nextElement();
            if (anInterface.isUp()) {
                Enumeration<InetAddress> addr = anInterface.getInetAddresses();
                while (addr.hasMoreElements()) {
                    if (!(address = addr.nextElement()).isLoopbackAddress())
                        break;
                }
            }
        }
        jmdns = JmDNS.create(address, type);
        listener = new ServiceListenerClass();
        jmdns.addServiceListener(type, listener);
}

public static class ServiceListenerClass implements ServiceListener {
    public void serviceAdded(ServiceEvent event) {
        event.getDNS().requestServiceInfo(event.getInfo().getServer(), event.getName(), true);
    }

    public void serviceRemoved(ServiceEvent event) {
        System.out.println((count--) + " " + event.getInfo().getName());
    }

    public void serviceResolved(ServiceEvent event) {
        System.out.println((count++) + " :Res: " + event.getInfo().getName() + " " + event.getInfo().getPort() + " " + event.getInfo().getApplication()
                + " " + event.getInfo().getDomain() + " " + event.getInfo().getKey());
        for (InetAddress address : event.getInfo().getInetAddresses())
            System.out.println(address.getHostAddress());
    }
}

}

4

1 回答 1

0

没有保证: JmDNS.create是非阻塞的,阻塞的就是jmdns.registerService()方法。

于 2012-09-07T05:36:42.753 回答