Android - socket timeout

I have weird socket behavior. I set the timeout to 5 seconds using setSoTimeout. It should be a lot of time in my situation. According to the java online documentation, should be discarded SocketTimeoutExceptionif it expires. It also states that the socket is still valid. So I want to catch him, and then continue. However, instead of an internal catch, an external catch IOExceptioncatches the calculus, and when I log the data, they say it was SocketTimeoutException. Another perplexity is that I change the timeout from 5 seconds to say 15 seconds, and write down the amount of time it takes for each read, the times are always in milliseconds, never even getting close to a second. Any ideas GREAT appreciated.

ReadThread code snippet

@Override
public void run()
{
    try
    {
        while (true)
        {
            byte[] sizeBuffer = new byte[BYTES_FOR_MESSAGE_SIZE];

            int bytesRead = this.inputStream.read(sizeBuffer);

            int length = 0;

            for (int i = 0; i < BYTES_FOR_MESSAGE_SIZE; i++)
            {
                int bitsToShift = 8 * i;
                int current = ((sizeBuffer[i] & 0xff) << bitsToShift);
                length = length | current;
            }

            byte[] messageBuffer = new byte[length];


            this.socket.setSoTimeout(5000); //5 second timeout

            try
            {
               this.inputStream.read(messageBuffer);
            }
            catch(java.net.SocketTimeoutException ste)
            {
               Log.e(this.toString(), "---- SocketTimeoutException caught ----");
               Log.e(this.toString(), ste.toString());
            }

        }
    }
    catch (IOException ioe)
    {
       Log.e(this.toString(), "IOException caught in ReadThread");
       Log.e(this.toString(), ioe.toString());
       ioe.printStackTrace();
    }
    catch (Exception e)
    {
       Log.e(this.toString(), "Exception caught in ReadThread");
       Log.e(this.toString(), e.toString());
       e.printStackTrace();
    }

    this.interfaceSocket.socketClosed();

}// end run
+3
source share
2 answers

I agree with Brian. You probably get a timeout on the first read, not seconds. The one-time timeout remains valid until you change it again.

Your second read request, in which you read the β€œmessage,” seems to suggest (a) that he will read the entire message and (b) that he will time out if the entire message does not arrive within 5 seconds. This does not work. This will be a timeout if nothing arrives within 5 seconds, otherwise it will read everything that arrived, up to message.length. But it can only be one byte.

You must use the DataInputStream.readFully()entire message to read, and you need to completely review your timeout strategy.

+2

, , catch - this.inputStream.read(). : , .

, ? , , . , . , , SoTimeout (, ).

, -Rad

+1

Source: https://habr.com/ru/post/1770179/


All Articles