Note: This tutorial assumes that you have completed the previous tutorials: Understanding Service Types.

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

Code Sample

   1 import ros.zeroconf.jmdns.Zeroconf;
   2 import org.ros.message.zeroconf_comms.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).

   1 for ( DiscoveredService discovered_service : discovered_services ) {
   2     myPrinter(discovery.toString(discovered_service));
   3 }

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 zeroconf_jmdns_demos (pc) and also zeroconf_android_jmdns_demos (android).

Wiki: zeroconf_jmdns/Tutorials/Service Discovery via Polling (last edited 2012-01-04 02:03:57 by DanielStonier)