JmDNS service discovery in client-server

Richard Stokes picture Richard Stokes · Nov 17, 2011 · Viewed 11.2k times · Source

I'm trying to enable service discovery in my client-server application using JmDNS. I fully understand service registry on the server side, with code that resembles this:

JmDNS jmdns = JmDNS.create(localhost);
jmdns.register(serviceInfo);

However, I'm having trouble figuring out how to have my client retrieve the port number and IP address from the registered service and use this data to open a TCP connection. I've searched for examples of how to use JmDNS but to no avail. Can anyone here give me some basic examples? Or if anyone has any links to good resources/tutorials on JmDNS could they please provide them?

Note: JmDNS is a neccessity here, so I would appreciate answers pertaining only to JmDNS and not offering an alternative. Also, I have looked at the JmDNS API extensively, and still can't figure it out, so please don't post a link to the docs as a resource.

Thanks.

Answer

yorkw picture yorkw · Nov 19, 2011

Server side:

mdnsServer = JmDNS.create(localhost);
// Register a test service.
ServiceInfo testService = ServiceInfo.create("my-service-type", "Test Service", 6666, "test service");
mdnsServer.registerService(testService);

Client side:

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();

Once you have the URL http://192.168.11.2:6666/myTestService, you can parse/use it open socket connection. Hope that help.