前段时间要用到JmDNS就去找了些资料,讲的也算详细,但有些问题不是很清晰,这里附上一份比较详细的使用说明:
首先,需要Jmdns的library,然后引入
import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceListener; import javax.jmdns.ServiceTypeListener;
private JmDNS mJmdns; private static final String JMDNS_SERVER_TYPE = "_http._tcp.local."; // 服务类型 private WifiManager.MulticastLock lock; // 组播锁
需要特别注意,对网络的操作需要开子线程
private class JmdnsAsyncTask extends AsyncTask<String, Integer, Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); lock = mWifiManager.createMulticastLock("multicast.test"); lock.setReferenceCounted(false); lock.acquire(); } @Override protected Boolean doInBackground(String... params) { try { mJmdns = JmDNS.create(); Log.i("JMDNS", "create jmdns"); } catch (IOException e) { e.printStackTrace(); Log.i("JMDNS", "create error"); return false; } return true; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (result) { //监听服务 Log.i("JMDNS", "add servicelistener"); mJmdns.addServiceListener(JMDNS_SERVER_TYPE, mlistener); } } }
监听服务
ServiceListener mlistener = new ServiceListener() { public void serviceResolved(ServiceEvent ev) { Log.i("JMDNS", "Service resolved:" + " name:" + ev.getInfo().getName() + " port:" + ev.getInfo().getPort() + " IP: " + ev.getInfo().getInetAddresses()[0].getHostAddress()); addDevices(ev.getInfo().getName(), ev.getInfo().getInetAddresses()[0].getHostAddress()); } public void serviceRemoved(ServiceEvent ev) { Log.i("JMDNS", "Service removed:" + ev.getName()); } public void serviceAdded(ServiceEvent event) { Log.i("JMDNS", "request "); mJmdns.requestServiceInfo(event.getType(), event.getName(), 1); } };
private void releaseJmdns() { new Thread(new Runnable() { @Override public void run() { mJmdns.removeServiceListener(JMDNS_SERVER_TYPE, mlistener); try { mJmdns.close(); } catch (IOException e) { e.printStackTrace(); } if (lock != null) { lock.release(); lock = null; } } }); }
以上就是整个JmDNS的使用过程,同时我尝试自己用Multicast组播做一个接收消息的客户端,实际调试过程中,像华为,OPPO这些品牌的手机一直接收不到组播消息,
起初认为是定制OS关闭了组播功能,最终却发现跟组播地址有关系,查询并使用JmDNS的组播地址224.0.0.251后就可以收到组播消息。