通过UDP

时间:2015-11-03 20:47:49

标签: java

我在客户端有这样的数组

int arr [] = new int [] {1,6,3,2,9};

我如何通过UDP将其发送到SERVER?以及如何在SERVER端读取它?

1 个答案:

答案 0 :(得分:1)

将数组转换为字节数组,然后发送字节数组。接收器将字节数组转换回int [];

您可以使用类DataOutputStream来创建字节数组。

 ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    int len = 0;
    in protokollVersion = 1;
    // Write a version, in case you want to change your format later, such that 
    // the receiver has a chance to detect which format version is used.
    dos.writeInt(protokollVersion);
    if (arr != null) {
      len = arr.length;
    }
    dos.writeInt(arr.length);
    for (int i = 0; i  < len; i++) {
        dos.writeInt(arr[i]);
    }
    dos.close();
    byte[] bytes = bos.getBytes();

在接收器端,使用DataInputStream(byte[] bytes)DataInputStream.readInt()读取字节数组。