从android平台发送UDP数据包

时间:2012-05-15 15:46:19

标签: android udp

我正在尝试在Android平板电脑上构建UDP客户端。应用程序可以创建一个socket juste,但是当我尝试发送它时:

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弹出一个新窗口,说“找不到源”,我在LogCat中打印出来了这个:

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

我想知道我正在使用的端口是否被阻止或者是否阻止了我的UDP连接(因为我尝试了许多不同的端口都具有相同的结果)。我问这个是因为LogCat(BlockGuardOS)可能表明它阻塞了一些输入/输出

这是实际的初始化:

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();
        }
    }

1 个答案:

答案 0 :(得分:6)

android.os.NetworkOnMainThreadException

不再允许您从主(UI)线程进行网络连接。你总是在文档中对它进行警告,但它现在主动被困。

在SO和其他来源中已经多次讨论过该主题。