简体   繁体   中英

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.

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.

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.

Is there something other then ObjectOutputStream that can be used for this?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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