How to receive data using UDP in Android?

I use the following code to get data from a specific port. It does not work in Android. But sending data to a specific port works 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);
    }
  }
}
+3
source share
2 answers

If you are using an emulator, you may need to set up redirection , remember that the emulator is located behind a virtual router.

In other words, enter these commands in:

telnet localhost 5554
redir add udp:9876:9876

and try again.

+5
source

Port Numbers Used

Create Datagram Package

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

Call function below via AsyncTask

Create a function to get 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";


}
0
source

Source: https://habr.com/ru/post/1751398/


All Articles