简体   繁体   English

使用 InputStreamReader 从套接字接收 utf-8 字符串?

[英]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. inFromDevice 是从接受的 ServerSocket 获取的 InputStream。

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)该代码大部分时间都在工作并返回消息,但有时我收到的消息小于 msgLength (根据协议这是错误的)

An example from the log is Actual chars read: 1020 char array length: 1391日志中的一个示例是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? Java 中是否有任何已知问题可能导致这种情况?

An InputStreamReader will only block until it can read one character into the buffer, or detect EOF. InputStreamReader只会阻塞,直到它可以将一个字符读入缓冲区或检测到 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.如果您的协议指示要发送的字符串的长度,则接收器需要循环,跟踪剩余的字符数,直到所有字符都被读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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