简体   繁体   中英

How to receive data using UDP in Android?

I use the following code to receive the data from a particular port. It's not working in Android. But sending data to particular port is working fine.

public class UDPDemo extends Activity {
  private TextView tv;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tv = (TextView)findViewById(R.id.recv_message);
    try {
      DatagramSocket clientsocket=new DatagramSocket(9876);
      byte[] receivedata = new byte[1024];
      while(true)
      {
        DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
        Log.d("UDP", "S: Receiving...");
        clientsocket.receive(recv_packet);
        String rec_str = new String(recv_packet.getData());
        tv.setText(rec_str);
        Log.d(" Received String ",rec_str);
        InetAddress ipaddress = recv_packet.getAddress();
        int port = recv_packet.getPort();
        Log.d("IPAddress : ",ipaddress.toString());
        Log.d(" Port : ",Integer.toString(port));
      }
    } catch (Exception e) {
      Log.e("UDP", "S: Error", e);
    }
  }
}

If you are using the emulator you may need setup redirects , remember the emulator is behind a virtual router.

In other words, type these commands in;

telnet localhost 5554
redir add udp:9876:9876

and try again.

Used Port numbers

Create Datagram packet

 try {
            mDataGramSocket = new DatagramSocket(Config.PORT_NUMBER);
            mDataGramSocket.setReuseAddress(true);
            mDataGramSocket.setSoTimeout(1000);
        } catch (SocketException e) {
            e.printStackTrace();
        } 

Call below function through AsyncTask

Create Function to receive infinitely

public void receive() {


    String text;

    byte[] message = new byte[1500];
    DatagramPacket p = new DatagramPacket(message, message.length);



    try {


        while (true) {  // && counter < 100 TODO
            // send to server omitted
            try {
                mDataGramSocket.receive(p);
                text = new String(message, 0, p.getLength());
                // If you're not using an infinite loop:
                //mDataGramSocket.close();

            } catch (SocketTimeoutException | NullPointerException e) {
                // no response received after 1 second. continue sending

                e.printStackTrace();
            }
        }


    } catch (Exception e) {

        e.printStackTrace();
        // return "error:" + e.getMessage();
        mReceiveTask.publish("error:" + e.getMessage());
    }

    // return "out";


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM