服务器端:
mdnsServer = JmDNS.create(localhost);
// Register a test service.
ServiceInfo testService = ServiceInfo.create("my-service-type", "Test Service", 6666, "test service");
mdnsServer.registerService(testService);
客户端:
private ServiceListener mdnsServiceListener = new ServiceListener() {
public void serviceAdded(ServiceEvent serviceEvent) {
// Test service is discovered. requestServiceInfo() will trigger serviceResolved() callback.
mdnsService.requestServiceInfo(Constants.mdnsServiceType, serviceEvent.getName());
}
public void serviceRemoved(ServiceEvent serviceEvent) {
// Test service is disappeared.
}
public void serviceResolved(ServiceEvent serviceEvent) {
// Test service info is resolved.
String serviceUrl = serviceEvent.getInfo().getURL();
// serviceURL is usually something like http://192.168.11.2:6666/my-service-name
};
mdnsService = JmDNS.create();
mdnsService.addServiceListener("my-service-type", mdnsServiceListener);
ServiceInfo[] infos = mdnsService.list(Constants.mdnsServiceType);
// Retrieve service info from either ServiceInfo[] returned here or listener callback method above.
mdnsService.removeServiceListener("my-service-type", mdnsServiceListener);
mdnsService.close();
获得 URLhttp://192.168.11.2:6666/myTestService
后,您可以解析/使用它打开的套接字连接。希望有所帮助。