Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过UDP发送数组(非数组列表)_Java - Fatal编程技术网

Java 通过UDP发送数组(非数组列表)

Java 通过UDP发送数组(非数组列表),java,Java,我在客户端有这样的数组 int arr[]=新的int[]{1,6,3,2,9} 如何通过UDP将其发送到服务器?如何在服务器端读取它?将数组转换为字节数组,然后发送字节数组。接收器将字节数组转换回int[] 您可以使用类DataOutputStream创建字节数组 ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos);

我在客户端有这样的数组

int arr[]=新的int[]{1,6,3,2,9}


如何通过UDP将其发送到服务器?如何在服务器端读取它?

将数组转换为字节数组,然后发送字节数组。接收器将字节数组转换回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();
ByteArrayOutputStream bos=newbytearrayoutputstream();
DataOutputStream dos=新的DataOutputStream(bos);
int len=0;
在protokolversion中=1;
//编写一个版本,以防以后要更改格式,以便
//接收器有机会检测所使用的格式版本。
dos.writeInt(protokolversion);
如果(arr!=null){
len=arr.长度;
}
dos.writeInt(arr.length);
对于(int i=0;i

在接收器端,使用
DataInputStream(byte[]bytes)
DataInputStream.readInt()

读取字节数组。您能告诉我如何转换它吗?因为我没有从谷歌搜索中得到多少帮助。