Search code examples
javaandroidandroid-asynctaskudpmotionevent

Too many AsyncTask's with UDP (DatagramSocket) throwing Exception when executed


I'm having a problem with my "Remote" App. What i want to do is to use my phone as a touchscreen to control the mouse cursor of my PC, which works so far, with the small problem that after moving the cursor around too much, i get an Exception.

The following code has only the most important snippets.

On my phone i have the following "Touchscreen"-Area:

RelativeLayout mouse = (RelativeLayout) findViewById(R.id.relative_layout_mouse);
    mouse.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent e) {
            int action = e.getAction();
            if (action == MotionEvent.ACTION_MOVE) { 
                int historySize = e.getHistorySize();
                if(historySize > 0){
                    //calculations on how to get x and y differences between current x/y and previous (historySize-1) x/y
                    new ClientUDPTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{difference_x, difference_y});
                }
            }
            return true;
        }
    });

Which sends the many small coordination changes to my AsyncTask when the mouse is moved:

public class ClientUDPTask extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String[] params) {
    ByteBuffer buffer = ByteBuffer.wrap(new byte[7]);
    //put the coordinates into the ByteBuffer...
    byte[] bytes = buffer.array();
    InetAddress adress = null;
    DatagramSocket socket = null;
    try {
        socket = new DatagramSocket();
        adress = InetAddress.getByName("192.168.1.108");
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, adress, 9000);
        socket.send(packet);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

And then on my Server i use those to move the Cursor:

public class UDPServer {

private DatagramSocket socket;

public void listen() {
    try {
        socket = new DatagramSocket(9000);
        byte[] buffer = new byte[7];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        while (true) {
            try {
                socket.receive(packet);
                byte[] data = packet.getData();
                //get coordinates out of bytearray...
                Robot robot = new Robot();
                int newX = x - Integer.valueOf(x);
                int newY = y - Integer.valueOf(y);
                robot.mouseMove(newX, newY);
            } catch (AWTException e) {
                e.printStackTrace();
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Now, as you can guess, when moving the mouse around much, many Tasks get created that send those snippets of data to the Server until i get this Exception:

java.net.SocketException: socket failed: EMFILE (Too many open files)
    at libcore.io.IoBridge.socket(IoBridge.java:623)
    at java.net.PlainDatagramSocketImpl.create(PlainDatagramSocketImpl.java:93)
    at java.net.DatagramSocket.createSocket(DatagramSocket.java:157)
    at java.net.DatagramSocket.<init>(DatagramSocket.java:80)
    at java.net.DatagramSocket.<init>(DatagramSocket.java:65)
    at com.example.johnsmith.remote.ClientUDPTask.doInBackground(ClientUDPTask.java:31)
    at com.example.johnsmith.remote.ClientUDPTask.doInBackground(ClientUDPTask.java:15)
    at android.os.AsyncTask$2.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
Caused by: android.system.ErrnoException: socket failed: EMFILE (Too many open files)
    at libcore.io.Posix.socket(Native Method)
    at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:282)
    at libcore.io.IoBridge.socket(IoBridge.java:608)
    ... 11 more

This exception points to:

socket = new DatagramSocket();

in ClientUDPTask.java

During moving LogCat shows me network usage of ~1 KB/s. It all works over my WiFi.

I already had this problem before when i used TCP instead of UDP. That was incredibly slow though, although i was also not using .executeOnExecutor(...). There are countless apps on the playstore that do this Remote-Thingie and it's super smooth, but how do they do that?

What's my mistake?


Solution

  • Try using a single DatagramSocket on the client side instead of creating a new one for each DatagramPacket you want to send. Or close the socket after you're finished with it with socket.close();. I think you're just opening too many sockets.