gpt4 book ai didi

java - Android 设备收不到多播包

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:02:40 28 4
gpt4 key购买 nike

我正在开发一个聊天应用程序,Android 客户端将在其中使用多播 (UDP) 交换 IP。

每个设备都会在一个单独的线程中将其 ip 发送给多个客户端(所有运行此应用程序的设备)。将有另一个接收器线程将监听这些多播数据包。这是我的代码。

//组播代码。

DatagramSocket socket = new DatagramSocket(9898);
byte buff[] = ip.getBytes();
DatagramPacket packet = new DatagramPacket(buff, buff.length, InetAddress.getByName("224.0.0.1"),9999);
socket.send(packet);
socket.close();

//接收方代码

MulticastSocket socket = new MulticastSocket(9999);
InetAddress group = InetAddress.getByName("224.0.0.1");
socket.joinGroup(group);

DatagramPacket packet;

byte[] buf = new byte[256];
byte b = 'x'; //just a separator for time being
Arrays.fill(buf,b);
packet = new DatagramPacket(buf, buf.length);
String received= "";
while(received!=null)
{
socket.receive(packet);
received = new String(packet.getData());
received = received.substring(0,received.indexOf('x'));
this.setIp(received);
System.out.println("Address: " + received);
}

socket.leaveGroup(group);
socket.close();

问题是每个设备都会打印自己的地址。它似乎从不听其他多播包(我的意思是它也应该打印其他 ip)。我还收到以下日志,不确定是否相关。

11-04 23:56:17.985: I/OSNetworkSystem(603): mcastAddDropMembership interfaceIndex=0

任何帮助将不胜感激。

最佳答案

您需要获得一个 MulticastLock在您的应用中,这将允许您的应用接收未明确发送到网络上此设备的数据包。

需要的权限:

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

示例代码:

// Acquire multicast lock
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifi.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();

//Do some mutlicast job here
... ...

// Once your finish using it, release multicast lock
if (multicastLock != null) {
multicastLock.release();
multicastLock = null;
}

关于java - Android 设备收不到多播包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13221736/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com