Yanu312
Yanu312

Reputation: 1

Java - Passing an ArrayList of Objects through TCP

I still new to Java and have an exercise where I have a TCP connection between a Client and a Server.

On the Client side I have an ArrayList of Shape Objects, where I add a new Triangle, Rectangle, etc and add them to this ArrayList. When I open the connection to the server I am having problems passing the ArrayList.

Do you reckon I should convert the ArrayList to strings before passing to the Server side?

Thanks

Upvotes: 0

Views: 288

Answers (3)

fireandfuel
fireandfuel

Reputation: 732

Make sure that your objects are serializable. You don't need to convert the ArrayList to String.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691765

TCP allows sending bytes from a client to a server. You want to pass a List<Shape>. You thus need a way to transform a List<Shape> into bytes.

There are several common ways to do that:

  • represent your shapes as an XML document
  • represent your shapes as a JSON document
  • represent your shapes as a String or array of bytes using a custom format
  • use native Java serialization, that can transform any Serializable object to bytes

The last one is the easiest one, but it won't allow sending the shapes to anything other than another Java program that also has the Shape classes that the client has in its classpath.

Upvotes: 1

GhostCat
GhostCat

Reputation: 140457

The point is that both sides just deal with raw bytes on a socket level. This means : you have to * serialize * your data.

Thus: look into Java serialization and ObjectInput/OutputStreams!

The one thing to be aware of : your shape class needs to be serializable! Then anything else is merely about using existing well-documented libraries!

Upvotes: 0

Related Questions