对于一项任务,我们正在尝试设置多个 Android 设备以通过本地 WiFi 网络从笔记本电脑接收 UDP 广播。
什么有效:
- 两台笔记本电脑上的 Python 终端能够相互发送和接收 UDP 广播或单播。
- Android 设备可以接收直接发送到其 IP 的 UDP 消息
什么不起作用:
- Android 设备(LG/Google Nexus 4)未收到 UDP 广播消息(另一台运行 Python 的笔记本电脑收到)
有什么建议吗?这是我们每个组件的来源(无耻地从互联网上借来)
Python接收广播
import select, socket
port = 50000
bufferSize = 1024
ip = '0.0.0.0'
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((ip, port))
while True:
msg, result = s.recvfrom(bufferSize)
pr
int "Received message: ", msg
Python发送广播
# Send UDP broadcast packets
port = 50000
import sys, time
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
data = repr(time.time()) + '\n'
s.sendto(data, ('192.168.1.255', port))
安卓
private void receiveUDP() {
final String[] text = new String[1];
final int server_port = 50000;
// create buffer
final byte[] message = new byte[1500];
final DatagramPacket p = new DatagramPacket(message, message.length);
// listen for message, put in buffer
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Log.d(Main.class.getName(), "Created socket");
DatagramSocket s = new DatagramSocket(server_port);
s.receive(p);
text[0] = new String(message, 0, p.getLength());
Log.d(Main.class.getName(), "message:" + text[0]);
s.close();
}
} catch (IOException e) {
Log.e(this.getClass().getName(), "An unexpected error occurred", e);
}
}
}).start();
}
重申一下,唯一不起作用的是在 Android 上接收 UDP 广播 - 它可以接收到其 IP 的单个 UDP 消息,而 Python 终端确实接收来自另一台笔记本电脑的 UDP 广播......
有什么建议吗?
更新
我看到我们应该使用 MulticastLock - 我现在已经尝试过了,但它仍然不起作用。这是新的安卓代码:
private void receiveUDP() {
final String[] text = new String[1];
final int server_port = 50001;
// create buffer
final byte[] message = new byte[1500];
final DatagramPacket p = new DatagramPacket(message, message.length);
// listen for message, put in buffer
new Thread(new Runnable() {
@Override
public void run() {
DatagramSocket s = null;
while (true) {
try{
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock lock = wifi.createMulticastLock("Main");
lock.acquire();
s = new DatagramSocket(server_port, InetAddress.getByName("192.168.1.13"));
Log.d(Main.class.getName(), "Created socket");
s.receive(p);
lock.release();
text[0] = new String(message, 0, p.getLength());
Log.d(Main.class.getName(), "message:" + text[0]);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "Received message: "+text[0], Toast.LENGTH_SHORT).show();
}
});
} catch (SocketException e) {
Log.e(Main.class.getName(), "An unexpected error occurred", e);
} catch (IOException e) {
Log.e(Main.class.getName(), "An unexpected error occurred", e);
} finally {
if (s != null) s.close();
Log.d(Main.class.getName(), "Closing socket");
}
}
}
}).start();
}