Dan Dickerson
Dan Dickerson

Reputation: 43

Android Datagram Sockets not working

I am trying to implement basic Datagram Sockets in Android. I am starting with one of the samples available on the web:

String messageStr="Hello Android!";
int server_port = 54372;
try {
  DatagramSocket s = new DatagramSocket();
  InetAddress local = null;
  local = InetAddress.getByName("192.168.100.127");
  int msg_length=messageStr.length();
  byte[] message = messageStr.getBytes();
  DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
  s.send(p);
} catch (SocketException e) {
  e.printStackTrace();
} catch (UnknownHostException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

I have enables the INTERNET permissions in AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>

The program dies when it hits the s.send(p) command.

What am I missing? It must be something obvious.

Upvotes: 1

Views: 4266

Answers (1)

ja_mesa
ja_mesa

Reputation: 1969

You are getting an error which you are not catch-ing: NetworkOnMainThreadException. You should do all networking staff in another Thread or AsyncTask.

For example:

class MyThread extends Thread
{
    @Override
    public void run()
    {
        UDPSend();
    }

    void UDPSend()
    {
        String messageStr = "Hello Android!";
        int server_port = 54372;
        try
        {
            DatagramSocket s = new DatagramSocket();
            InetAddress local = null;
            local = InetAddress.getByName("192.168.1.57");
            int msg_length = messageStr.length();
            byte[] message = messageStr.getBytes();
            DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
            s.send(p);
            android.util.Log.w("UDP", "Works fine!");
        }
        catch (SocketException e)
        {
            e.printStackTrace();
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            android.util.Log.w("UDP", "Catched here.");
            e.printStackTrace();
        }
    }

}

To execute the thread in your main thread: new MyThread().start();

UPDATE:

UDP receiver in an Asynctask: This is a real example of an app. I've removed some lines which are not relevant. I show you the doInBackgroud, the one that receive the UDP packets.

@Override
protected Void doInBackground(Void... urls)
{
    DatagramSocket socketUDP;

    try
    {
        socketUDP = new DatagramSocket(5050);
        socketUDP.setSoTimeout(5000);

        // set it to true if you want to receive broadcast packets
        socketUDP.setBroadcast(false); 
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }

    byte[] buff = new byte[512];
    DatagramPacket packet = new DatagramPacket(buff, buff.length);
    try
    {
        asyncTask_UDP_is_running=true;
        // Keep running until application gets inactive
        while (aplicationActive)
        {
            try
            {
                socketUDP.receive(packet);
                android.util.Log.w("UDP", "got a packet");
            }
            catch (java.net.SocketTimeoutException ex)
            {
                // timeout
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return null; 
            }
        }
    }
    finally
    {
        asyncTask_UDP_is_running=false;
    }
    return null;
}

}

Upvotes: 1

Related Questions