一、jmDNS:JAVA实现(JmDNS)
-
引入pom
<!-- https://mvnrepository.com/artifact/javax.jmdns/jmdns --> <dependency><groupId>javax.jmdns</groupId><artifactId>jmdns</artifactId><version>3.4.1</version> </dependency>
-
服务发现
import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException;import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceListener;public class ExampleServiceDiscovery {private static class SampleListener implements ServiceListener {@Overridepublic void serviceAdded(ServiceEvent event) {System.out.println("Service added: " + event.getInfo());}@Overridepublic void serviceRemoved(ServiceEvent event) {System.out.println("Service removed: " + event.getInfo());}@Overridepublic void serviceResolved(ServiceEvent event) {System.out.println("Service resolved: " + event.getInfo());}}public static void main(String[] args) throws InterruptedException {try {// Create a JmDNS instanceJmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());// Add a service listener // jmdns.addServiceListener("_http._tcp.local.", new SampleListener());jmdns.addServiceListener("_coap._udp.local.", new SampleListener());// Wait a bitThread.sleep(30000);} catch (UnknownHostException e) {System.out.println(e.getMessage());} catch (IOException e) {System.out.println(e.getMessage());}} }
-
服务发布
import java.io.IOException; import java.net.InetAddress;import javax.jmdns.JmDNS; import javax.jmdns.ServiceInfo;public class ExampleServiceRegistration {public static void main(String[] args) throws InterruptedException {try {// Create a JmDNS instanceJmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());// Register a serviceServiceInfo serviceInfo = ServiceInfo.create("_coap._udp.local.", "example", 5683, "path=index.html");jmdns.registerService(serviceInfo);// Wait a bitThread.sleep(25000);// Unregister all servicesjmdns.unregisterAllServices();} catch (IOException e) {System.out.println(e.getMessage());}} }
-
发现端日志
-
监控局域网avahi发布的服务
二、avahi:Linux下实现(avahi - mDNS/DNS-SD)
avahi安装
sudo apt-get install avahi-deamon avahi-utils
# 无法安装可以试试:sudo apt-get install avahi
发布服务
avahi-publish-service avahi_light _coap._udp 5683 "/mylight" --sub _floor1._sub._coap._udp
发现服务(再起一个客户端连接)
avahi-browse -a --resolv
发现服务日志
服务关闭日志