简体   繁体   中英

how to receive udp data in android?

Hi I am new to android.From android i can send data to another port.But i am not able to receive the data using udp in android.How to receive data by using udp in android emulator? can anyone help me to receive the udp data in android?

Code is here

DatagramSocket clientsocket=new DatagramSocket(4900);
byte[] receivedata=new byte[1024];
while(true)
{
DatagramPacket recv_packet=new DatagramPacket(receivedata, receivedata.length);
textview.setText("UDP S: Receiving...");
clientsocket.receive(recv_packet);
String rec_str=new String(recv_packet.getData());           
textview.setText(" Received String "+rec_str); 
}

client wait to receive for a long time on ==> clientsocket.receive(recv_packet);

how to receive udp data in android?

Emulator has it's own virtual network you have redirect ports from your host

telnet localhost 5554
redir add udp:4900:4900

see Android Emulator

I had the same problem, and I discovered that the problem was because of the android emulator redirections and a bug.

First of all, if you use an android emulator device with a level of API 25+ you will need to start the device without the "AndroidWifi" feature or you will not to able to communicate with your device because of a bug https://issuetracker.google.com/issues/37095198

For doing this:

cd "C:\Program Files (x86)\Android\android-sdk\emulator"
emulator.exe -avd <name+of+your+device> -feature -Wifi

After that, as Gawcio say, you will need to redirige the desired ports of your localhost to your emulator device

telnet localhost 5554
auth <your+code+here>
redir add udp:<origin+port>:<destination+port>

Finally, you need to redirige the UDP packets from your local IP address (192.168.1.X) to yout localhost (127.0.0.1) or the emulated device will not receive the packet. For doing this you can create a simple UDP rediriger or use the program i created to do the same thing https://github.com/danidis91/Port-forward-UDP

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