Java:将字符串转换为ByteBuffer和相关问题 [英] Java: Converting String to and from ByteBuffer and associated problems

查看:199
本文介绍了Java:将字符串转换为ByteBuffer和相关问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Java NIO作为我的套接字连接,我的协议是基于文本的,所以我需要能够将字符串转换为ByteBuffers,然后将它们写入SocketChannel,并将传入的ByteBuffers转换回字符串。目前,我使用这个代码:

I am using Java NIO for my socket connections, and my protocol is text based, so I need to be able to convert Strings to ByteBuffers before writing them to the SocketChannel, and convert the incoming ByteBuffers back to Strings. Currently, I am using this code:

public static Charset charset = Charset.forName("UTF-8");
public static CharsetEncoder encoder = charset.newEncoder();
public static CharsetDecoder decoder = charset.newDecoder();

public static ByteBuffer str_to_bb(String msg){
  try{
    return encoder.encode(CharBuffer.wrap(msg));
  }catch(Exception e){e.printStackTrace();}
  return null;
}

public static String bb_to_str(ByteBuffer buffer){
  String data = "";
  try{
    int old_position = buffer.position();
    data = decoder.decode(buffer).toString();
    // reset buffer's position to its original so it is not altered:
    buffer.position(old_position);  
  }catch (Exception e){
    e.printStackTrace();
    return "";
  }
  return data;
}

这大部分时间都在工作,但我怀疑这是首选或最简单的)方式来做这个转换的每个方向,或者如果有另一种方式来尝试。偶尔,似乎随机,调用 encode() decode()会抛出一个
java.lang.IllegalStateException:当前状态= FLUSHED,新状态= CODING_END 异常或类似,即使我每次转换完成时使用一个新的ByteBuffer对象。我需要同步这些方法吗?任何更好的方式之间转换字符串和字节缓冲区?感谢!

This works most of the time, but I question if this is the preferred (or simplest) way to do each direction of this conversion, or if there is another way to try. Occasionally, and seemingly at random, calls to encode() and decode() will throw a java.lang.IllegalStateException: Current state = FLUSHED, new state = CODING_END exception, or similar, even if I am using a new ByteBuffer object each time a conversion is done. Do I need to synchronize these methods? Any better way to convert between Strings and ByteBuffers? Thanks!

推荐答案

查看 CharsetEncoder CharsetDecoder API说明 - 您应该遵循方法调用的特定顺序以避免此问题。例如, CharsetEncoder

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:


  1. 通过 reset 方法,除非它以前没有被使用;

  2. 调用更多次,只要额外的输入可用,为endOfInput参数传递 false ,填充输入缓冲区并在调用之间刷新输出缓冲区;

  3. 最后调用 encode 方法,为endOfInput参数传递 true 然后

  4. 调用 flush 方法,使编码器可以将任何内部状态刷新到输出缓冲区。

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

顺便说一下,这是我使用NIO的相同方法,虽然我的一些同事将每个字符直接转换为一个字节的知识,他们只是使用ASCII,我可以想象可能是更快。

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

这篇关于Java:将字符串转换为ByteBuffer和相关问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆