I try to receive datagram by multicast.
I try to use Java as below:
class looperThread extends Thread {
public void run() {
try {
byte[] buffer = new byte[140];
int port = 24680;
String address = "224.0.0.10";
try {
socket = new MulticastSocket(port);
InetAddress add = InetAddress.getByName(address);
socket.joinGroup(add);
while (true) {
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, add, port);
socket.receive(packet);
area.append("Received from " + packet.getAddress().toString() + "\n");
} catch (UnknownHostException ue) {
}
}
} catch (java.net.BindException b) {
}
} catch (IOException e) {
System.err.println(e);
}
}
}
It works.
But I modify the code to Android as below.
Below on onCreate():
Thread mClockThread = new looperThread();
mClockThread.start();
class looperThread extends Thread {
@Override
public void run() {
WifiManager wifi = (WifiManager) getSystemService(getApplicationContext().WIFI_SERVICE);
MulticastLock mLock = wifi.createMulticastLock("mylock");
mLock.acquire();
try {
byte[] buffer = new byte[140];
int port = 24680;
String address = "224.0.0.10";
try {
MulticastSocket socket = new MulticastSocket(port);
InetAddress add = InetAddress.getByName(address);
socket.joinGroup(add);
while (true) {
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, add, port);
socket.receive(packet);
System.out.println("Received from " + packet.getAddress().toString() + "\n");
} catch (UnknownHostException ue) {
}
}
} catch (java.net.BindException b) {
}
} catch (IOException e) {
System.err.println(e);
}
}
}
In fact, it send several datagrams.
But it only receive one or part of datagrams.
And in Java code, it receives all.
How should I do to improve?
I think it may cause by unstable wireless.
You should try to change a new AP to test.
It may your Android phone’s network interface controller conflict with the AP.