简体   繁体   中英

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

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.

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!

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

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