Comic Sans MS Lover
Comic Sans MS Lover

Reputation: 1729

Android multicast - Sometimes receive is blocking thread

I believe the MulticastSocket.receive method is blocking my thread. It won't work again unless the app goes to onResume(), which restarts the thread. How can I fix this?

Receiver Code

private class ReceiverThread extends Thread
{

    private static final String TAG = ComMessageReceiver.TAG + "Thread";

    private WifiManager wifiManager;
    private MulticastSocket multicastSocket;
    private InetSocketAddress groupInetSocketAddress;
    private boolean joinedGroup = false;

    public ReceiverThread(String group, int port, int timeout) throws IOException {

        super();

        wifiManager = (WifiManager) App.context.getSystemService(Context.WIFI_SERVICE);
        groupInetSocketAddress = new InetSocketAddress(InetAddress.getByName(group), port);
        multicastSocket = new MulticastSocket(port);
        multicastSocket.setSoTimeout(timeout);
    }

    public ReceiverThread() throws IOException {

        this(Config.multicastAddress, Config.multicastPort, DEFAULT_TIMEOUT);
    }

    @Override
    public void run() {

        Log.d(TAG, "started");

        while (!this.isInterrupted()) {

            if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {

                if (!joinedGroup) {

                    try {
                        multicastSocket.joinGroup(groupInetSocketAddress,
                                NetworkInterface.getByInetAddress(getWifiInetAddress()));

                        wifiManager.createMulticastLock("ComMessageReceiverLock").acquire();

                        joinedGroup = true;

                    } catch (IOException ex) {

                        Log.e(TAG, "Failed to join Multicast group: " + ex.getMessage());
                    }
                }

                try {

                    byte[] buffer = new byte[256];

                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                    multicastSocket.receive(packet);

                    Log.d(TAG, "Message received: " + message.message);

                } catch (SocketTimeoutException e) {
                } catch (IOException ex) {

                    multicastSocket = null;

                    Log.e(TAG, ex.getMessage());
                }
            } else
                joinedGroup = false;
        }
    }

}

Multicast code

private class ComServerThread extends Thread {

    private static final String LOG = "ComServerThread";
    private final static long INTERVAL = 1000;
    private boolean alert = true;

    private DatagramSocket socket;

    public ComServerThread() {

        try {

            socket = new DatagramSocket(5500);
        } catch (SocketException ex) {

            Log.e(LOG, "Error opening socket: " + ex.getMessage());
        }
    }

    @Override
    public void run() {

        while (!this.isInterrupted()) {

            try {

                try {

                    sleep(INTERVAL);
                } catch (InterruptedException ex) {

                    Log.e(LOG, "Interrupted the thread sleep! not cool: "
                            + ex.getMessage());
                }

                byte[] buffer;

                String msg = "Test"

                buffer = msg.getBytes();

                InetAddress group = InetAddress.getByName("230.0.0.1");

                DatagramPacket packet = new DatagramPacket(buffer,
                        buffer.length, group, 5500);
                socket.send(packet);

                Log.d(LOG, "Packet sent.");

            } catch (UnknownHostException ex) {

                Log.e(LOG, "Oops. Invalid host: " + ex.getMessage());
            } catch (IOException ex) {

                Log.e(LOG,
                        "Something bad happened while sending the packet. Take a look: "
                                + ex.getMessage());
            }
        }
    }
}

Upvotes: 1

Views: 1505

Answers (1)

user207421
user207421

Reputation: 311018

You are correct, it is a blocking method.

If you set a read timeout, it will throw a SocketTimeoutException, which you appear to be ignoring, so your code will just loop and block again.

You don't need to join the multicast group every time around the loop: that is just wasteful.

Upvotes: 2

Related Questions