I'm trying to get two phones to send/receive data with broadcast UDP. I've followed many guides and solutions, for example https://code.google.com/p/boxeeremote/wiki/AndroidUDP.
The relevant parts of the code are:
Receiver:
WifiManager wifiManager=(WifiManager) MyActivity.context.getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock multicastLock=wifiManager.createMulticastLock("Walkie");
if (multicastLock == null)
return;
multicastLock.acquire();
while(receives) {
try {
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
MyActivity.socket.receive(packet);
Log.d("Receiver", "Packet Received");
buffer=packet.getData();
//do work with buffer
} catch(IOException e) {
continue; //it just timed out
}
}
multicastLock.release();
Sender:
while(sends) {
//acquire buffer
packet = new DatagramPacket(
buffer,
buffer.length,
MyActivity.getBroadcastAddress(), //from the site mentioned above
MyActivity.port);
MyActivity.socket.send(packet);
}
Socket:
socket = new DatagramSocket(port);
socket.setSoTimeout(100);
socket.setBroadcast(true);
If I remove the socket.setBroadcast(true);
and replace broadcast IP with second phone's IP, everything works. With broadcast, none of the phones receive any packet. The phones are Samsung Core Plus (Android 4.2.2) and Sony Xperia Z1 Compact (4.4.4). I'm completely lost at this point.
0 comments:
Post a Comment