JmDNS service discovery in client-server

戏子无情 提交于 2019-12-30 00:44:34

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8174234/jmdns-service-discovery-in-client-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!