JmDNS service discovery in client-server

南笙酒味 提交于 2019-11-30 03:54:36
yorkw

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.

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