问题描述
我是flutter新手,最近在实现局域网内的flutter通讯。关于在Android设备上等待接收UDP信息,Android/iOS发送UDP信息(非广播模式),在Android-Android代码运行是没有问题的,但在Android-iOS的情况下,iOS无法发送,也不报任何错误,只是在socket.send返回0;查看源码返回0代表被block,但查询google或者baidu等都无法找到相关答案。请问如何解决?
PS:在iOS设备,是能收到Android设备发出的broadcast信息。
问题出现的环境背景及自己尝试过哪些方法
相关代码
接收端是Android代码
/**
* 基于udp的组网连接, 接收局域网内投屏申请
*/
public class UDPClientRunnable implements Runnable {
private static final String TAG = "UdpClientThread";
private boolean isRunning = false;
private OnUdpConnectListener mListener;
public UDPClientRunnable(OnUdpConnectListener listener) {
this.mListener = listener;
}
@Override
public void run() {
isRunning = true;
try {
DatagramSocket socket = new DatagramSocket(Constants.UDP_CLIENT_PORT); //8856
byte buf[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
String ip;
while (isRunning) {
socket.receive(dp);
ip = new String(buf, 0, dp.getLength());
Log.e(TAG, "receive connect ip : " + ip);
final String finalIp = ip;
MyApplication.mHandler.post(new Runnable() {
@Override
public void run() {
mListener.udpConnectSuccess(finalIp);
}
});
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "udp server stop by close socket");
} finally {
Log.e(TAG, "udp server close");
isRunning = false;
}
}
public void stopThread() {
isRunning = false;
}
}
以下为flutter发送端代码
class UDPStartRequest {
final String targetIp;
final int port;
UDPStartRequest(this.targetIp, this.port);
void start() async {
InternetAddress targetAddress = InternetAddress(targetIp);
String localIp = await Utils.getLocalIp(); //已经确保这个地址是同一个网段下
// (await NetworkInterface.list()).first.addresses.first.address;
print('localIp $localIp connect to $targetIp');
RawDatagramSocket.bind(InternetAddress.anyIPv4, 0).then((socket) {
int ret = socket.send(utf8.encode(localIp), targetAddress, port);
print('Start request from ${socket.address.address}:${socket.port}, ret = $ret');
});
}
}
已经找到解决方案,可能原因是第一次send udp包无法触发iOS系统的”允许连接到附近设备权限“,只能通过flutter channel用源生代码连接一遍,并且用户允许了权限,才能继续是用flutter的udp功能进行通讯。