How to receive multiple responses from UDP broadcast


How to receive multiple responses from UDP broadcast



I have a case in which i need to send a broadcast a UDP request in the wifi on a specific port and the specific devices i am calling should return some info so i can determine how much are they in this network.
So far i have this:


public class UDP extends AsyncTask<Void, Void, String> {

@Override
protected String doInBackground(Void... voids) {
String text = "";
int server_port = 7432;
DatagramPacket receivePacket = null;
DatagramSocket clientSocket = null;
try {
clientSocket = new DatagramSocket();
clientSocket.setSoTimeout(5);
InetAddress IPAddress = InetAddress.getByName("255.255.255.255");
byte sendData = ("02904").getBytes();
byte receiveData = new byte[12];
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, server_port);
clientSocket.send(sendPacket);
receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
Log.e("Receiving response", "Response");
text = new String(receivePacket.getData());
clientSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
Log.e("Receiving response", "Response");
assert receivePacket != null;
text = new String(receivePacket.getData());
clientSocket.close();
} catch (IOException e) {
Log.e("Receiving response", "Response");
assert receivePacket != null;
text = new String(receivePacket.getData());
clientSocket.close();
}
return text;
}

@Override
protected void onPostExecute(String s) {
Log.e("Socket response", s);
}
}



Testing with 1 device in the network is returning weird triangles with question marks in them (i am not sure but i guess something with encoding) but my actual problem is that i do not know how to get a list for example and fill it up with all the devices that responded. How to get every response and save it as a different response so i can parse them?
Everything i know for the request is in the code. Response will be byte with 12 as size and device specific info in it.


byte









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV