如何从UDP广播接收多个响应

时间:2018-06-27 18:29:25

标签: java android sockets udp

我有一种情况,我需要在wifi上的特定端口上发送UDP请求的广播,并且我正在呼叫的特定设备应返回一些信息,以便我可以确定它们在此网络中的数量。 到目前为止,我有这个:

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

在网络中使用1台设备进行测试正在返回带有问号的怪异三角形(我不确定,但我猜有带编码的东西),但我的实际问题是我不知道如何获取列表并填充与所有响应的设备有关。如何获得每个响应并将其另存为其他响应,以便我可以解析它们? 我所知道的所有要求都在代码中。响应将是byte[],其中包含12个大小和特定于设备的信息。

0 个答案:

没有答案