java BufferedReader specific length returns NUL characters

后端 未结 2 756
遇见更好的自我
遇见更好的自我 2021-01-29 03:10

I have a TCP socket client receiving messages (data) from a server. messages are of the type length (2 bytes) + data (length bytes), delimited by STX & ETX characters.

2条回答
  •  伪装坚强ぢ
    2021-01-29 03:49

    The InputStream read method may return short reads; you must check the return value to determine how many characters were read, and continue reading in a loop until you get the number you wanted. The method may block, but it only blocks until some data is available, not necessarily all the data you requested.

    Most people end up writing a "readFully" method, like DataInputStream, which reads the amount of data expected, or throws an IOException:

    static public int readFully(InputStream inp, byte[] arr, int ofs, int len) throws IOException {
        int                                 rmn,cnt;
    
        for(rmn=len; rmn>0; ofs+=cnt, rmn-=cnt) {
            if((cnt=inp.read(arr,ofs,rmn))==-1) { 
                throw new IOException("End of stream encountered before reading at least "+len+" bytes from input stream"); 
                }
            }
        return len;
        }
    

提交回复
热议问题