0
votes

I have a box, which sends UDP response after receiving UDP packet. I finally found example how to implement UDP server. It receives UDP packets okay.

There is a button in my app. If I tap it I sends UDP packet to the box, but I don't get the resonse. I see that the box receives this packet from my Android device and sends the response. My UDP client is below:

    public class AsyncSendUdp extends AsyncTask<String, Void, Boolean> {
    InetAddress inet_addr;
    DatagramSocket socket;

    @Override
    protected Boolean doInBackground(String... arg0) {
        byte[] ip_bytes = new byte[]{(byte) 192, (byte) 168, (byte) 0, (byte) 11};
        try {
            inet_addr = InetAddress.getByAddress(ip_bytes);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        char[] bufc = {1, 2, 3, 4};
        byte[] buffer = new byte[4];
        for (int i = 0; i < 4; i++) {
            buffer[i] = (byte) bufc[i];
        }
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length, inet_addr, 0xbac0);
        try {
            socket = new DatagramSocket();
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
}

I send as follows:

new AsyncSendUdp().execute("mmm");

I don't understand where is the problem. Any ideas please!

1

1 Answers

1
votes

You're never actually reading for incoming messages. You'll want something like:

byte[] inBuffer = new byte[N];
DatagramPacket inPacket = new DatagramPacket(inBuffer, inBuffer.length);
while (!exitCondition) {
    socket.receive(inPacket);
    // do something with your received packet
}