对于作业,我们正尝试设置多个Android设备,通过本地WiFi网络从笔记本电脑接收UDP广播。
什么有效:
什么行不通:
有什么建议吗?这是我们每个组件的来源(无耻地借用互联网)
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))
的Android
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 - 我现在已经尝试过这个但它仍然不起作用。这是新的Android代码:
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();
}
答案 0 :(得分:1)
有些手机,包括Nexus 4,似乎锁定了UDP接收广播功能。解决方案是使用不同的手机。例如,它适用于廉价的华为G300