如何在Android中使用UDP接收数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3102048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:41:40  来源:igfitidea点击:

How to receive data using UDP in Android?

android

提问by 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.

我使用以下代码从特定端口接收数据。它在 Android 中不起作用。但是将数据发送到特定端口工作正常。

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

回答by ktingle

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.

然后再试一次。

回答by Jayakrishnan PM

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

通过 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";


}