0

I'm trying to build a UDP client on an android tablet. The application can create a socket juste fine, but when I try to send it:

public void SendMessage( String message )
    {
        sendBuffer = message.getBytes();

        packet = new DatagramPacket( sendBuffer, sendBuffer.length, address, 4445 );
        //packet = new DatagramPacket( sendBuffer, sendBuffer.length, address, port );

        try 
        {
            socket.send( packet );
        } 
        catch (IOException ioe) 
        {
            Log.d( "NETWORK", "Failed to send UDP packet due to IOException: " + ioe.getMessage() );
            ioe.printStackTrace();
        }
        catch( Exception e )
        {
            Log.d( "NETWORK", "Failed to send UDP packet due to Exeption: " + e.getMessage() );
            e.printStackTrace();
        }
    }

Eclipse pops a new window saying "source not found" and I have this printed out in the LogCat:

android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
at ...

I'm wondering if maybe the port I'm using is blocked or can something block my UDP connection (because I've tried many different ports all with the same result). I'm asking this because of the LogCat (BlockGuardOS) which could indicate it's blocking some input/output

This is the actual initialization is here:

public ClientSocketThread( String address, int port )
    {       
        this.port = port;

        try 
        {
            this.address = InetAddress.getByName( address );
            Log.d( "NETWORK", "Address successfully resolved" );
        } 
        catch( UnknownHostException ue ) 
        {
            ue.printStackTrace();
            Log.d( "NETWORK", "Failed to resolve ip address due to UnknownException: " + ue.getMessage() );
        }

        try 
        {
            this.socket = new DatagramSocket();
            Log.d( "NETWORK", "UDP Socket successfully created" );
        } 
        catch( SocketException se ) 
        {
            Log.d( "NETWORK", "Failed to create socket due to SocketException: " + se.getMessage() );
            se.printStackTrace();
        }
    }
TurnsCoffeeIntoScripts
  • 3,868
  • 8
  • 41
  • 46

1 Answers1

6
android.os.NetworkOnMainThreadException

You are no longer allowed to do networking from the main (UI) thread. You were always warned against it in the documentation, but it is now pro-actively trapped.

The topic has been covered numerous times here on SO and in other sources.

Chris Stratton
  • 39,853
  • 6
  • 84
  • 117
  • 3
    For the future people that find this thread, [this](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) provides a good example of how to correctly implement the AsyncTask so you're not processing on the main UI thread. – Wyatt Oct 09 '12 at 01:10