简体   繁体   English

通过TCP发送两种不同类型的数组

[英]Sending two different type of arrays over TCP

I'm currently writing a network application that has to be able to send one 2D array of ints and one regular array of objects over a TCP connection. 我目前正在编写一个网络应用程序,它必须能够通过TCP连接发送一个二维int数组和一个常规对象数组。

My first, and only, solution so far is using ByteArrayOutputStream and ObjectOutputStream but this will only work if I send a specific type of array that I typecast back on the other side. 到目前为止,我的第一个也是唯一的解决方案是使用ByteArrayOutputStream和ObjectOutputStream,但是这只有在我发送一个特定类型的数组时才会起作用,我在另一方面回击它。

Now this would work 现在这会奏效

baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);

oos.writeObject(2dArray);
Byte[] send = baos.toByteArray();

But I can only use this if I only send 2d int-arrays since i need to typcast this on the other end and, as previously stated, I want to be able to send both 2d and regular arrays of different types. 但是我只能使用这个,如果我只发送2d int-arrays,因为我需要在另一端打字,并且如前所述,我希望能够发送不同类型的2d和常规数组。

Is there something other then ObjectOutputStream that can be used for this? 还有其他可以用于此的ObjectOutputStream吗?

When you receive an object on the remote side you can check which kind of an object it is. 当您在远程端收到一个对象时,您可以检查它是哪种对象。 For example you can write: 例如,您可以写:

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;
}

If you use something else for communication you'll still have to indicate the type of array you are sending in some way, so you'll always have the same problem. 如果你使用其他东西进行通信,你仍然需要以某种方式指出你要发送的数组类型,所以你总会遇到同样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM