java - 通过数据报包发送数组的最佳方式是什么?

标签 java arrays datagram

假设我有一个字符串:你好!我必须做这一切:

  1. 将字符串转换为字节数组
  2. 发送字节数组
  3. 将其转换回字符串(供以后使用)

这是我的代码...

//Sender
String send = "Hello!";
byte[] data = send.getBytes();
DatagramPacket packetOut = new DatagramPacket(data, data.length); //send blah blah

//Receiver
//blah blah receive it
String receive = new String(packetIn.getData()); //convert it back

对整数数组执行此操作的快速而优雅的方法是什么?

最佳答案

对于 int[],您可以使用 ObjectOutputStream 进行序列化,但更快的方法可能是使用 ByteBuffer。

public static byte[] intsToBytes(int[] ints) {
    ByteBuffer bb = ByteBuffer.allocate(ints.length * 4);
    IntBuffer ib = bb.asIntBuffer();
    for (int i : ints) ib.put(i);
    return bb.array();
}

public static int[] bytesToInts(byte[] bytes) {
    int[] ints = new int[bytes.length / 4];
    ByteBuffer.wrap(bytes).asIntBuffer().get(ints);
    return ints;
}

关于java - 通过数据报包发送数组的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12954424/

相关文章:

arrays - F#:为什么 Array.createZero 这么快?

c# - C#中的UDP套接字?

sockets - 如何拆分接收到的 boost asio udp 套接字联合数据报

arrays - 使用 map 在数组中创建出现的哈希值

python - 获取numpy中多维切片沿特定轴的索引

java - 测试DatagramSockets的传输

java - 将 8 位索引颜色转换为 RGB

java - 用户创建时出现 Liferay 异常 com.liferay.portal.GroupFriendlyURLException

java - android ImageButton 在 api 8 中设置 alpha

java - 运行时如何知道EJB是什么样的?