P.Andrews P.Andrews - 11 months ago 51
Java Question

Transfer type double[] over network

I want to transfer the type double[] over a network, and then somehow manage to transfer it back into a double[] in the receiving side. I am not entirely sure how to do this. I tried to convert the String received to a char[] and then parse all the chars to a double[]. However this did not work, the double had different data. I need to do this to make a network protocol for opencv, to transfer Mat's easily.

So this is how the data gets sent:

private void send_info(int row,int col, double[] data) {
//Convert data to String, separated by : to indicate change
//char[] sendit = data.toString().toCharArray();

And this is how it is received:

private void setInfo(String input) {
input = input.trim();
String inputs[] = input.split(":");
int row = Integer.parseInt(inputs[1]);
int col = Integer.parseInt(inputs[3]);
//double[] data = magic(inputs[4]);
// What I need ^

Answer Source

Don't convert them at all. Waste of time and space. Just do it directly. To send double[] doubles:

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
dos.writeInt(doubles.length); // send the array length
for (d : doubles)

To read:

DataInputStream din = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
double[] doubles = new double[dis.readInt()];
for (int i = i; i < doubles.length; i++)
    doubles[i] = dis.readDouble();

Or you can use ObjectOutputStream.writeObject() and ObjectInputStream.readObject() to write and read the entire array at once. Or you can use NIO and DoubleBuffer: left as an exercise for the reader.