本地网络中的设备发现

ano*_*les 8 networking android discovery

我目前正在开发一个使用SDK> = 16的Android应用程序,它应该能够使用WiFi无线电在局域网中发现不同的Android设备(后来也是iOS设备).

我的第一个猜测是使用在我的三星Galaxy S2上无效的多播:仅在从同一设备发送时才接收数据包.

我的第二个猜测是使用有限的IP地址范围主动扫描网络并等待适当的响应.不幸的是,这意味着网络使用DHCP来寻址IP地址.

上述解决方案似乎都不是完美的解决方案.

我目前解决的第一个猜测是:

public class MulticastReceiver extends AsyncTask<Activity, Integer, String> {

    private static final String host = "224.1.1.1";
    private static final int port = 5007;
    private static final String TAG = "MulticastReceiver";

    protected String doInBackground(Activity... activities) {
        WifiManager wm = (WifiManager)activities[0].getSystemService(Context.WIFI_SERVICE);
        WifiManager.MulticastLock multicastLock = wm.createMulticastLock("mydebuginfo");
        multicastLock.acquire();
        String message = "Nothing";

        if (multicastLock.isHeld()) {
            Log.i(TAG, "held multicast lock");
        }

        try {
            InetAddress addr = InetAddress.getByName(host);
            MulticastSocket socket = new MulticastSocket(port);
            socket.setTimeToLive(4);
            socket.setReuseAddress(true);
            socket.joinGroup(addr);

            byte[] buf = new byte[5];
            DatagramPacket recv = new DatagramPacket(buf, buf.length, addr, port);
            socket.receive(recv);
            message = new String(recv.getData());
            socket.leaveGroup(addr);
            socket.close();
        } catch (Exception e) {
            message = "ERROR " + e.toString();
        }

        multicastLock.release();

        return message;
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码导致阻塞行socket.receive(recv); 如果我指定超时,则会收到超时异常.

Gab*_*han 1

查看http://developer.android.com/training/connect-devices-wireless/index.html 它提到了两种查找本地服务的方法 - NSD 和 wifi direct。