A
A
Artem2012-09-27 00:23:55
Java
Artem, 2012-09-27 00:23:55

Random packet loss in multicast on Android?

I need to multicast messages between Android and Windows. But there is a problem: for some reason, when trying to transfer packages from Windows to Android, packages are often lost (60 percent offhand). Moreover, if there are no problems between two Windows devices (Win7 and XP). And if you transfer data from Android to PC, everything works fine too. It turns out that the problem is in the receiver on Android. It arises in general haphazardly: either one packet breaks through, then immediately from a dozen or one and a half can be sent without problems. What can be wrong?
My android code:

private void MulticastStart() {
  try {
    WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
    if(wifi!=null) {
      MulticastLock multicastLock = wifi.createMulticastLock("MyApp");
      multicastLock.acquire();
    }
    multicastGroupAddr=InetAddress.getByName("239.123.126.129");
    multicastSocket = new MulticastSocket(PORT);
    multicastSocket.joinGroup(multicastGroupAddr);
  } catch (IOException e) {
    e.printStackTrace();
  }
}

public void MulticastHandler() {
  Thread thread = new Thread() {
    @Override
    public void run() {
      try {
        while (true) {
          byte[] buffer = new byte[1024];
          DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
          multicastSocket.receive(datagramPacket);
          String ip=datagramPacket.getAddress().getHostAddress();
          String message=new String(buffer, 0, datagramPacket.getLength());
          Log.d("MyApp", ip+": "+message);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  };
  thread.start();
}

public void MulticastStop() {
  if(multicastLock!=null && multicastLock.isHeld()) multicastLock.release();
  if(multicastSocket!=null && !multicastSocket.isClosed()) {
    try {
      multicastSocket.leaveGroup(multicastGroupAddr);
    } catch (IOException e) {
      e.printStackTrace();
    }
    multicastSocket.close();
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question