Android应用程序未接收UDP广播数据包

时间:2014-02-03 13:44:53

标签: android

我无法使用以下代码接收UDP广播数据包 我正在使用DatagramSocket在ip:port 239.255.255.250:1900上发送广播。

我有以下用于接收M-SEARCH /广播消息的代码。

public class MainActivity extends Activity 
{
    final int SERVER_PORT = 1900;
    DatagramSocket mSocket = null;
    WifiManager.MulticastLock mMulticastLock = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        Log.d("","MainActivity onCreate");

        setContentView(R.layout.main_layout);
    }

    @Override
    protected void onResume() 
    {
        super.onResume();

        WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        if(wifi != null)
        {
            mMulticastLock = wifi.createMulticastLock("multi_lock");
            mMulticastLock.acquire();
        }
        startReceiver();
    }

    @Override
    protected void onPause() 
    {
        super.onPause();

        if(mMulticastLock != null)
        {
            mMulticastLock.release();
            mMulticastLock = null;
        }
    }

    public void startReceiver()
    {
        Thread thread = new Thread( new Runnable() 
        {
            @Override
            public void run() 
            {
                byte[] message = new byte[1024];

                try
                {
                    mSocket = new DatagramSocket(SERVER_PORT);
                    DatagramPacket packet = new DatagramPacket(message, message.length);

                    Log.d("", "waiting on receive for broadcast...");

                    if((mSocket != null)&&(packet != null))
                        mSocket.receive(packet);

                    String pktData = new String(packet.getData());
                    String ipString = packet.getAddress().toString();
                    Log.d("", "ipString:"+ipString);
                    Log.d("", "pktData:"+pktData);

                    Toast.makeText(getApplicationContext(), "RECEIVED ipString:"+ipString+" pktData:"+pktData, Toast.LENGTH_LONG).show();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    if( mSocket != null)
                        mSocket.close();
                }
            }
        });
        thread.start();
    }

    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
        if( mSocket != null )
            mSocket.close();
    }
}

但不知何故,我无法使用上述代码接收UDP广播消息 我尝试了多种方法,但没有任何工作,我也采取了发送端的数据包捕获,我可以看到网络上的数据包,但我的接收端没有收到这些数据包。

1 个答案:

答案 0 :(得分:0)

实际上,你混淆了广播和多播地址。 对于多播地址,您必须使用java.net.MulticastSocket。 见:http://developer.android.com/reference/java/net/MulticastSocket.html

相关问题