Android TCP app hanging on inStream.readline()

前端 未结 2 1588
花落未央
花落未央 2021-01-21 17:02

This is a continuation of this question because it my orginal question was answered, but it did not solve the bug.

Question:

  • How do I fix the code hanging
2条回答
  •  一个人的身影
    2021-01-21 17:41

    You need to check if there is data available:

    if (InStream.available > 0) {                                                      
       String modifiedSentence = InStream.readLine();
       sendMessageToAllUI(0, MAINACTIVITY_SET_TEXT_STATE, "appendText" , "IN FROM SERVER: " + modifiedSentence); 
    }
    

    But to be honest, even that is not ideal because you have no gurantee that the eond-of-line will have been received. If the server sends a few bytes but never sends the end-of-line then you will still be blocking forever. Production socket code should never rely on readLine but instead read into a buffer and check that buffer for end-of-line (or whatever criteria your protocol needs).


    Didn't read closely enough, I thought InStream was an InputStream instance. InputStream has available. InputStreamReader has ready (which in turn calls InputStream.available. As long as you keep a refernce to either of these then you can see if data is available to be read.

提交回复
热议问题