Search code examples
androidmultithreadingudppacket

Android: Issue with simple UDP program


I am trying to get a good grasp of UDP on Android, so I am writing a small test program to set up 2 sockets on the same machine, send a packet and receive it. I thought it would be straight-forward, but something is going wrong. My code is:

DatagramSocket server;
DatagramSocket client;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Initialize a client socket and a server socket using UDP
    try {
     server = new DatagramSocket();
     client = new DatagramSocket();
} catch (SocketException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
}

 // Server will now send some data
  String data = "This is a test";
  DatagramPacket sendPacket = new DatagramPacket(data.getBytes(), data.length(),
       client.getInetAddress(), client.getLocalPort());
  try {
   server.send(sendPacket);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  // Client has to receive and read the data
  byte[] buf = new byte[1024];
  DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
  try {
   client.receive(receivePacket);
   byte[] receivedData = receivePacket.getData();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  server.disconnect();
  client.disconnect();
}

When I debug my code, it goes into the last try, in "client.receive(receivePacket);" but it never comes back from that function call. The packet seems to be never received, but I have a hard time finding why that is.

I hope someone could please help me fix this problem.

EDIT: New code using threads. Calling "recieve" before actually sending the packet. Trying to use AsyncTask.

public class udpexample extends Activity {

    DatagramSocket server;
    DatagramSocket client;

    String data = "This is a test";

    private static final String TAG = "UDPExampleActivity";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Log.i(TAG, "Starting");

        // Initialize a client socket and a server socket using UDP
        try {
            server = new DatagramSocket();
            client = new DatagramSocket();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        new ReceivePacket().execute();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // Server will now send some data
        DatagramPacket sendPacket = new DatagramPacket(data.getBytes(), data.length(),
                client.getInetAddress(), client.getLocalPort());
        try {
            Log.i(TAG, "About to send");
            server.send(sendPacket);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private class ReceivePacket extends AsyncTask<Void, Void, Void> {
        // Thread used to receive a packet

        @Override
        protected Void doInBackground(Void... params) {
            // Client has to receive and read the data
            byte[] buf = new byte[1024];            
            DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
            try {
                Log.i(TAG, "About to receive");
                client.receive(receivePacket);
                byte[] receivedData = receivePacket.getData();

                // Verify that the packet is identical to the one being sent
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Void result) {
            server.disconnect();
            client.disconnect();
        }
    } 
}

Still having the same issue, it stops and waits on receive and nothing happens.

Thank you very much,

Jary


Solution

  • I think you are sending a packet while receiver is not yet listening.

    Try first client.receive(..) and then server.send(..). That way client will be listening for incoming packets. Of course, you will have to run this in two different threads.