简体   繁体   English

Java-通过TCP传递对象的ArrayList

[英]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. 我还是Java的新手,并进行了一个练习,其中在客户端和服务器之间建立了TCP连接。

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. 在客户端,我有一个Shape Objects ArrayList,在其中添加了一个新的Triangle,Rectangle等,并将它们添加到此ArrayList中。 When I open the connection to the server I am having problems passing the ArrayList. 当我打开与服务器的连接时,我无法通过ArrayList。

Do you reckon I should convert the ArrayList to strings before passing to the Server side? 您认为我应该在传递给服务器端之前将ArrayList转换为字符串吗?

Thanks 谢谢

TCP allows sending bytes from a client to a server. TCP允许将字节从客户端发送到服务器。 You want to pass a List<Shape> . 您要传递List<Shape> You thus need a way to transform a List<Shape> into bytes. 因此,您需要一种将List<Shape>转换为字节的方法。

There are several common ways to do that: 有几种常见的方法可以做到这一点:

  • represent your shapes as an XML document 将形状表示为XML文档
  • represent your shapes as a JSON document 将形状表示为JSON文档
  • 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 使用本机Java序列化,可以将任何Serializable对象转换为字节

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. 最后一个是最简单的,但是它不允许将形状发送到另一个Java程序,该Java程序也具有客户端在其类路径中具有的Shape类。

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! 因此:研究Java序列化和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. 您无需将ArrayList转换为String。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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