Search code examples
javaandroidsocketstcptcpclient

Why does this use of Socket.setSoTimeout() not work?


This code snippet is from a TCP helper function I made in Android java:

            socket.setSoTimeout(2000);
            InputStream inStream = socket.getInputStream();
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
            true);

            out.println(message);

            BufferedReader input = new BufferedReader(new InputStreamReader(inStream));

            String tcpResult = "";

            if(lastCallMillis >= System.currentTimeMillis() - 100)
                Thread.sleep(100);

            tcpResult = input.readLine();

When the very first line is there, the one with "setSoTimeout", the method fails with an exception. When I do NOT set the timeout it works without a hitch.

Well.. almost I had to insert this part because if the socket was used quickly in a row it failed:

            if(lastCallMillis >= System.currentTimeMillis() - 100)
            Thread.sleep(100);

Anyway am I misunderstanding something about using java sockets or is it just horribly supported?


Solution

  • If you don't want a shot read timeout don't set a short read timeout. Adding sleeps to networking code never solves anything. It is just literally a waste of time. What you should have done was added the sleep time to the timeout. But even 2.1 seconds is ludicrously short for a read timeout. Try ten, or thirty.