网络服务发现并非始终有效

时间:2018-11-26 17:13:50

标签: java android service-discovery

我正在尝试制作一个Android应用程序,以使用NDS在LAN上发现mqtt代理的IP。我开始在MainActivity中发现服务:

NsdManager mNsdManager;
NsdManager.DiscoveryListener mDiscoveryListener;
NsdServiceInfo mService;
String serverUri;

public static final String SERVICE_TYPE = "_mqtt._tcp.";
public String myServiceName = "mqtt_broker";

public class MyResolveListener implements NsdManager.ResolveListener {

    @Override
    public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
        Log.e(TAG, "Resolve failed" + errorCode);
    }

    @Override
    public void onServiceResolved(NsdServiceInfo serviceInfo) {
        Log.e(TAG, "Resolve Succeeded. " + serviceInfo);
        mService = serviceInfo;
        serverUri = "ssl:/" + mService.getHost() + ":8883";
        mNsdManager.stopServiceDiscovery(mDiscoveryListener);
    }
}

public void searchServerIP()
{
    mNsdManager = (NsdManager)getSystemService(Context.NSD_SERVICE);
    mDiscoveryListener = new NsdManager.DiscoveryListener() {

        @Override
        public void onDiscoveryStarted(String regType) {
            // ...
        }

        @Override
        public void onServiceFound(NsdServiceInfo service) {
            if (service.getServiceName().contains(myServiceName)){
                mNsdManager.resolveService(service, new MyResolveListener());
            }
        }

        @Override
        public void onServiceLost(NsdServiceInfo service) {
            // ...
        }

        @Override
        public void onDiscoveryStopped(String serviceType) {
            // ...
        }

        @Override
        public void onStartDiscoveryFailed(String serviceType, int errorCode) {
            // ...
        }

        @Override
        public void onStopDiscoveryFailed(String serviceType, int errorCode) {
            // ...
        }
    };
    mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    searchServerIP();
}

我在某些设备上尝试了此代码:Xiaomi MI5(带有android 8.0),Xiaomi MI4(带有android 6.0)和Samsung GT-P5200(带有android 4.4.2)。该代码在所有设备上均有效,但是有时我找不到任何MDNS服务,并且我的App无法与服务器(经纪人MQTT)连接。有人有主意吗? 对不起,我的英语,谢谢您的时间。

0 个答案:

没有答案