在android上无法接收udp广播包

时间:2014-11-19 12:08:00

标签: java android

我正在尝试接收从另一个android机器发送的udp数据包.II可以通过java udp客户端程序接收相同的数据包,但同样不能在android上工作。这是我的代码:

//主要活动

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Log.v("Main Activity", "intialized started");
            list = (ListView) findViewById(R.id.listview1);

            mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wifiReciever = new WifiScanReceiver();
            mainWifiObj.startScan();
            Log.v("Main Activity", "MainActivity started");

            clientDatagramReceiver=new ClientDatagramReceiver();
            clientDatagramReceiver.start();


//clientdatagramreceiver class

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.SocketException;

    import android.util.Log;
    import android.widget.Toast;

    public  class ClientDatagramReceiver extends Thread {
        private DatagramSocket datagramsocket = null;
        private boolean bKeepRunning = true;
        InetAddress serverIP=null;

        public ClientDatagramReceiver() {
            try {
                datagramsocket = new DatagramSocket(7999);
                Log.v("ClientDatagramSender", "Socket Created");
            } catch (SocketException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.v("ClientDatagramSender", "Socket Unicast SET");
            }
        }

        public void run() {
            byte[] messageBytes = new byte[10];

            DatagramPacket packet = null;
            while(this.bKeepRunning) {
                packet = new DatagramPacket(messageBytes, 10);
                Log.d("ClientDatagramReceiver", "RECEIVING PACKET CREATED");
                try {
                    datagramsocket.receive(packet);
                    Log.d("ClientDatagramReceiver", "INCOMING PACKET RECEIVED");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                serverIP=packet.getAddress();
                Log.d("ClientDatagramReceiver", "IP ADDRESS of REMOTE SENDER: " + serverIP.getHostAddress());

                ServerIpHelper.setServerIP(serverIP);

                ClientDatagramSender.killAllThreads();
                Log.d("ClientDatagramReceiver", "STOPPING BROADCAST SERVICE");

                this.bKeepRunning = false;
                Log.d("ClientDatagramReceiver", "RECEIVER CLOSED");
            }
        }
    }

显示日志直到:"收到包裹创建"然而doenot接收数据包。 任何建议都会非常感激。 感谢

0 个答案:

没有答案