【问题标题】:Receiving a utf-8 string using InputStreamReader from a Socket?使用 InputStreamReader 从 Socket 接收 utf-8 字符串?
【发布时间】:2019-08-31 04:04:45
【问题描述】:

我正在尝试使用此代码从设备接收字符串:

        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;

inFromDevice 是从接受的 ServerSocket 获取的 InputStream。

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

日志中的一个例子是Actual chars read: 1020 char array length: 1391

我认为问题是由于网络问题或设备出现问题而导致的外部问题,但我需要对此有一些专家见解。 Java 中是否存在可能导致此问题的已知问题?

【问题讨论】:

  • 如果你特别想要 UTF-8,为什么不告诉InputStreamReader
  • 我敢打赌 msgLength 的单位是 bytes,那么你为什么希望 char 计数与 byte 相同计数,如果消息包含非 ASCII 字符并且编码是 UTF-8。你知道 UTF-8 是如何工作的,对吧?
  • @Andreas no 协议指定前 4 个字节是发送的 UTF-8 字符数。我没有告诉 InputStreamReader UTF-8,因为它是默认的。

标签: java sockets inputstream inputstreamreader


【解决方案1】:

InputStreamReader 只会阻塞,直到它可以将一个字符读入缓冲区或检测到 EOF。不能保证缓冲区会被填满。

如果您的协议指示正在发送的字符串的长度,则接收方需要循环,跟踪剩余的字符数,直到所有字符都被读取。

【讨论】:

  • 这似乎合乎逻辑,我会尝试一下,你建议一种干净的循环方式还是我应该使用其他类型的阅读器? @埃里克森
  • @alibttb 您可以执行类似CharBuffer expected = CharBuffer.wrap(cb); while (cb.hasRemaining()) r.read(expected); 的操作。在读取包含消息长度的ByteBuffer 的数据时,您应该执行类似操作。
  • 你的意思是CharBuffer expected = CharBuffer.wrap(cb); while (expected.hasRemaining()) { r.read(expected); }@erickson
  • @alibttb 是的,抱歉打错了。你说得对。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
相关资源
最近更新 更多