How to send a list of custom objects over a socket?

Tags:



public class shapeInfo {
    int x;
    int y;
    int z;
    int t;
    Color shapeColor;
    int shapeType;
}
static ArrayList<shapeInfo> shapeStack = new ArrayList<>();

How can I send elements of this ArrayList over a socket from a client to a server? I tried some structures but all needed one String to send.

Answer

The easiest way is to use object streams.

In order to do this, shapeInfo should be Serializable:

public class ShapeInfo implements Serializable{
    int x;
    int y;
    int z;
    int t;
    Color shapeColor;
    int shapeType;
}

Then, you can send it using an ObjectOutputStream:

Socket socket;//your socket
try(ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream())){
    oos.writeObject(shapeStack);
}

On the other side, you can receive it:

Socket socket;//your socket
try(ObjectInputStream oos=new ObjectInputStream(socket.getInputStream())){
    shapeStack=(ArrayList<ShapeInfo>)oos.readObject();
}

If you don’t want to implement Serializable or don’t want to use object streams, you can also sequentially send all attributes in the ArrayList of all objects using DataInputStream/DataOutputStreams.


Notes

Note that class names should be written PascalCase by convention.

You should also need to handle IOExceptions.

I did not initialize the socket connection in my example. You need to use an initialized socket connection for it to work.

You should use buffered streams for a better performance.

Variables in objects should be private and accessible using getters/setters.



Source: stackoverflow