0

Is there any good option to send broadcast message on UDP port while receiving data from other devices on the same port? I have this currently:

First I initialize 1 DiagramSocket for both reading and sending:

private void startSocket(){
    try {
        if(socket == null) {
            socket = new DatagramSocket(3040);
            socket.setBroadcast(true);
            socket.setReuseAddress(true);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

In first Thread I have reading/receiving for current socket:

public class Server implements Runnable {

    public Server(iBroadcastResponse iBResponse){
        BroadcastClass.this.iBResponse = iBResponse;
    }

    @Override
    public void run() {
        startSocket();
        while (DataHandler.isEmergencyMode.get() ) {
            try {                    
                byte[] buf = new byte[256];
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                if(socket == null)
                    return;
                 socket.receive(packet);
                String command = stringFromPacket(packet);
                Log.d(TAG, command);
                addToBroadcastCalls(command);
                if(iBResponse != null)
                    iBResponse.onResponse();

            } catch (Exception e) {
                Log.e(TAG, "Server: Error!\n");
            }
        }
        Log.e(TAG, "Stop!");
    }

    String stringFromPacket(DatagramPacket packet) {
        return new String(packet.getData(), 0, packet.getLength());
    }
}

If I run this, it works normally, reads receiving data. But if I try to send data in another thread:

socketThread = new Thread(){
            @Override
            public void run() {
                startSocket();
                String message = "Message";
                byte[] buf = message.getBytes();
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                try {
                    if(!socket.isConnected())
                        socket.connect(InetAddress.getByName("255.255.255.255"), 3040);
                    if (socket != null) {
                        socket.send(packet);
                    }
                    Log.d(TAG, "Send: " +message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        socketThread.start();

When .send() is called it stops receiving data from other devices so now it only send message but stops receiving it from other devices.

Is there any good solution to this problem?

Tomek
  • 557
  • 2
  • 7
  • 24

1 Answers1

0

This was the solution https://stackoverflow.com/a/25520279/1088975

I only changed

System.log...

To

Log.w(TAG, "Message...");

And I changed IP to be always "255.255.255.255" instead of

getBroadcastAddress()

which returns broadcast IP for current WIFI, which didn't work on my android devices

Tomek
  • 557
  • 2
  • 7
  • 24