我目前正在编写一个网络应用程序,它必须能够通过 TCP 连接发送一个 2D 整数数组和一个常规对象数组。
到目前为止,我的第一个也是唯一的解决方案是使用 ByteArrayOutputStream 和 ObjectOutputStream,但这只有在我发送在另一端类型转换回的特定类型的数组时才有效。
现在这可以工作了
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(2dArray);
Byte[] send = baos.toByteArray();
但是,如果我只发送 2d int 数组,我只能使用它,因为我需要在另一端进行打字,并且如前所述,我希望能够发送不同类型的 2d 和常规数组。
除了 ObjectOutputStream 之外还有其他东西可以用于此目的吗?
最佳答案
当您在远程端收到一个对象时,您可以检查它是什么类型的对象。例如你可以写:
Object received = in.readObject();
if (received instanceof int[]) {
// received 1d array
int[] array1D = (int[]) received;
} else if (received instanceof int[][]) {
// received 2d array
int[][] array2D = (int[][]) received;
}
如果您使用其他东西进行通信,您仍然必须以某种方式指示您要发送的数组的类型,因此您总是会遇到相同的问题。
关于java - 通过 TCP 发送两种不同类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19118329/