简体   繁体   中英

Receiving a utf-8 string using InputStreamReader from a Socket?

I'm trying to receive a string from a device using this code:

        byte[] buf = new byte[4];
        int read = inFromDevice.read(buf);
        Logger.getLogger(Utill.class.getName() + " DEBUG_ERR01").log(Level.INFO, "Bytes read: {0}", read);
        int msgLength = ByteBuffer.wrap(buf).getInt();
        Logger.getLogger(Utill.class.getName() + " DEBUG_ERR01").log(Level.INFO, "Message length: {0}", msgLength);
        Reader r = new InputStreamReader(inFromDevice);
        char[] cb = new char[msgLength];
        int actualCharsRead = r.read(cb);
        Logger.getLogger(Utill.class.getName() + " DEBUG_ERR01").log(Level.INFO, "Actual chars read: {0} char array length: {1}", new Object[]{actualCharsRead, cb.length});
        String msgText = String.valueOf(cb, 0, cb.length);
        Logger.getLogger(Utill.class.getName() + "Messages Loggining recieve: ").log(Level.INFO, msgText);
        return msgText;

the inFromDevice is and InputStream acquired from an accepted ServerSocket.

The code is working and returning messages most of the time, but some times I get messages smaller than msgLength (which is wrong according to the protocol)

An example from the log is Actual chars read: 1020 char array length: 1391

I think the problem is external due to a network problem or device is having an issue, but I need some expert insight on this. are there any known problems in Java that may cause this?

An InputStreamReader will only block until it can read one character into the buffer, or detect EOF. There is no guarantee that the buffer will be filled.

If your protocol indicates the length of the string being sent, the receiver needs to loop, tracking the number of characters remaining, until all have been read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM