【问题标题】:Getting string from netty ByteBuf从 netty ByteBuf 获取字符串
【发布时间】:2016-11-05 00:22:32
【问题描述】:

如何从网络ByteBuf 获取字符串?到目前为止,我能够逐个字符地获得它。有没有办法直接获取字符串对象?

// message is of type ByteBuf
for (int i = 0; i < message.capacity(); i++) {
    byte b = message.payload().getByte(i);
    System.out.print((char) b);
}

【问题讨论】:

    标签: java netty bytebuffer


    【解决方案1】:

    Take a look at this

    从那里您可以使用new String(byte[]) 或一些 Base64 解决方案(因为我假设它是二进制数据)

    【讨论】:

      【解决方案2】:

      使用提供的方法ByteBuf.toString(Charset)

      【讨论】:

        【解决方案3】:

        使用ByteBuf.readCharSequence()

        例子在这里:

        // here we use utf-8 decoding, you can choose the charset you want
        String s = ByteBuf.readCharSequence(length, Charset.forName("utf-8")).toString()
        

        注意ByteBuf.readCharSequence()返回java.lang.CharSequence,使用toString()得到String对象

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-18
          • 2017-03-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多