我创建了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());
}
}
}
答案 0 :(得分:0)
无保证:JmDNS.create
是非阻止的,阻塞的是jmdns.registerService()
方法。