| Note: This tutorial assumes that you have completed the previous tutorials: Understanding Service Types, Service Discovery via Polling. |
Service Discovery via Callbacks
Description: Shows how to do service discovery with jmdns using callbacks.Keywords: zeroconf jmdns
Tutorial Level: INTERMEDIATE
Contents
Notes
This is mostly working now - particularly for android systems however this part of the jmmdns code is still fairly experimental and will be likely to change. If you run into issues, please contact <d DOT stonier AT gmail DOT com>, we're working the jmdns developer to improve certain parts of the discovery mechanisms.
Code Sample
1 import java.util.ArrayList;
2 import ros.zeroconf.jmdns.Zeroconf;
3 import ros.zeroconf.jmdns.ZeroconfDiscoveryHandler;
4 import org.ros.message.zeroconf_comms.DiscoveredService;
5
6 class DiscoveryHandler implements ZeroconfDiscoveryHandler {
7 public DiscoveryHandler() {
8 this.discovered_services = new ArrayList<DiscoveredService>();
9 }
10 public void serviceAdded(DiscoveredService service) {
11 // custom handling code
12 }
13
14 public void serviceRemoved(DiscoveredService service) {
15 // custom handling code
16 }
17
18 public void serviceResolved(DiscoveredService service) {
19 // custom handling code
20 }
21 private ArrayList<DiscoveredService> discovered_services;
22 }
23
24 Zeroconf discovery = new Zeroconf();
25 DiscoveryHandler discovery_handler = new DiscoveryHandler();
26 zeroconf.setDefaultDiscoveryCallback(discovery_handler);
27 discovery.addListener("_ros-master._tcp","local");
Breaking it Down
Initialise the module:
Add a default discovery handler (written by yourself) (see further down for an example). This will be used to handle callbacks for every listener you add.
Alternatively, you can add specific handlers for specific listeners:
1 TCPDiscoveryHandler tcp_discovery_handler = new TCPMasterDiscoveryHandler();
2 discovery.addListener("_ros-master._tcp","local",tcp_discovery_handler);
3 UDPDiscoveryHandler udp_discovery_handler = new UDPMasterDiscoveryHandler();
4 discovery.addListener("_ros-master._udp","local",udp_discovery_handler);
Example
Example code can be found in zeroconf_android_master_browser (android).






