1

我正在尝试在网络上发现我的应用程序。所以我选择multicast技术。但它在Android中是不一致的。

允许

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

锁定多播过滤器

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mcastLock = wifiManager.createMulticastLock("SHAREALL_M_LOCK");
mcastLock.acquire();

发送多播

MulticastSocket socket = new MulticastSocket();
socket.joinGroup(InetAddress.getByName("224.0.0.5"));
DatagramPacket packet = new DatagramPacket(msg, msg.length, InetAddress.getByName("224.0.0.5"), 8092);
socket.send(packet);

接收多播

MulticastSocket socket = new MulticastSocket(8092);
socket.joinGroup(InetAddress.getByName("224.0.0.5"));
DatagramPacket packet = new DatagramPacket(data,data.length);
socket.receive(packet);

我已经在 Samsung Gallaxy SII 和 Moto G 中测试了这些代码。

4

0 回答 0