[英]Android broadcast receiver doesn't work: the binding failed and is unable to assign request address
對於一項作業,我嘗試設置Android設備以從筆記本電腦上的python程序接收UDP廣播。
python發送器將每隔5秒通過廣播發送一些數據,並且接收器有望接收和顯示數據。 但是,無法在android接收器上接收數據。 我目前正在使用Samsung S3作為我的Android設備進行測試。
確定的一個主要錯誤是綁定失敗並且無法分配請求地址。
以下是出於我的目的在網絡上找到的修改后的代碼。
# Send UDP broadcast packets
port = 50001
import sys, time
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
while 1:
data = repr(time.time()) + '\n'
print data
s.sendto(data, ('192.168.0.14', port))
time.sleep(5)
class receiveUDP implements Runnable {
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);
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.0.14"));
Log.d(MainActivity.class.getName(), "Created socket");
s.receive(p);
lock.release();
text[0] = new String(message, 0, p.getLength());
Log.d(MainActivity.class.getName(), "message:" + text[0]);
runOnUiThread(new Runnable() {
@Override
public void run() {
//Toast.makeText(context, "Received message: "+text[0], Toast.LENGTH_SHORT).show();
textResponse.setText(text[0]);
}
});
} catch (SocketException e) {
Log.e(MainActivity.class.getName(), "An unexpected error occurred", e);
} catch (IOException e) {
Log.e(MainActivity.class.getName(), "An unexpected error occurred", e);
} catch (SecurityException e) {
Log.e(MainActivity.class.getName(), "An unexpected error occurred", e);
} finally {
if (s != null) s.close();
Log.d(MainActivity.class.getName(), "Closing socket");
}
}
}
}
您是否在應用程序的清單文件中添加了android.permission.CHANGE_WIFI_MULTICAST_STATE?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.