Note: This tutorial assumes that you have completed the previous tutorials: Understanding Service Types, Publishing Services. |
Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags. |
Service Discovery via Polling
Description: Shows how to do service discovery with jmdns using a simple polling method.Keywords: zeroconf jmdns
Tutorial Level: INTERMEDIATE
Next Tutorial: Service Discovery via Callbacks
Contents
Code Sample
1 import com.github.ros_java.zeroconf_jmdns_suite.jmdns.Zeroconf;
2 import com.github.ros_java.zeroconf_jmdns_suite.jmdns.DiscoveredService;
3
4 Zeroconf discovery = new Zeroconf();
5 discovery.addListener("_ros-master._tcp","local");
6 while( true ) {
7 try {
8 List<DiscoveredService> discovered_services = discovery.listDiscoveredServices();
9 if ( discovered_services.size() > 0 ) {
10 for ( DiscoveredService discovered_service : discovered_services ) {
11 myPrinter(discovery.toString(discovered_service));
12 }
13 } else {
14 myPrinter("...");
15 }
16 Thread.sleep(2000L);
17 } catch (InterruptedException e) {
18 e.printStackTrace();
19 }
20 }
21 discovery.removeListener("_ros-master._tcp","local");
Breaking it Down
Initialise the zero-configuration module, optionally use one of the very crude loggers if you wish to see more information from the class.
1 import ros.zeroconf.jmdns.Zeroconf;
2 // standard output logging (System.out)
3 // import ros.zeroconf.jmdns.StandardLogger;
4 // android logging (view with 'adb logcat zeroconf:I *:S')
5 // import ros.zeroconf.android.jmdns.Logger
6
7 Zeroconf discovery = new Zeroconf();
8 // Zeroconf discovery = new Zeroconf(new StandardLogger());
9 // Zeroconf discovery = new Zeroconf(new Logger());
10
Add a service type to listen to.
1 discovery.addListener("_ros-master._tcp","local");
Retrieve the current list (cache) of discovered services.
1 List<DiscoveredService> discovered_services = discovery.listDiscoveredServices();
Print the list. Note that the list is already amalgamated for you to include all known addresses for each service (can potentially have one for ipv4/ipv6 and a pair for each interface locally).
Finally, you can remove a listener at any time, though the class will automatically clean up for you on exit.
1 discovery.removeListener("_ros-master._tcp","local");
Example
Example code can be found in the jmdns tutorials.