通过网络传递实体?
我研究 Java 网络有一段时间了。 我使用 ObjectInputStream 和 ObjectOutputStream 进行套接字之间的 I/O。
是否可以将实体或模型从服务器传输到客户端,反之亦然? 我怎样才能实现这个?我是否应该将实体或模型实现为可序列化?
非常感谢您的回复。
I have been studying Java networking for a while.
I am using ObjectInputStream and ObjectOutputStream for the I/O between sockets.
Is this possible to transfer a Entity or Model from server to client and vise versa?
How can I implement this? Am I suppose to implement the Entity or Model to Serializable?
Your response is highly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定你用大写 E 实体和大写 M 模型来表示什么样的特殊事物;这些术语在 Java 中没有任何固定的、特权的含义(尽管它们可能与某个 API 或框架相关)。一般来说,如果您仅指某些特定的 Java 对象,那么是的,您可以发送任何类型的对象以这种方式存在,是的,它们需要实现可序列化。唯一的限制是,如果这些对象包含其值在管道另一端没有意义的成员,例如文件路径等。
请注意,如果您发送一个对象,您最终将发送它的所有其他对象也持有非瞬态引用。
I am not sure what sort of special thing you mean to denote by capital-E Entity and capital-M Model; these terms don't have any fixed, privileged meaning in Java (although they might with respect to a certain API or framework.) In general, if by these you just mean some specific Java objects, then yes, you can send any sort of objects this way, and yes, they would be required to implement Serializable. The only limitations would be if these objects contained members whose values wouldn't make sense on the other end of the pipe -- like file paths, etc.
Note that if you send one object, you'll end up sending every other object it holds a non-transient reference to, as well.
首先...为什么通过 I/O 流发送对象? XML 出了什么问题?
但是,只要发送方可以序列化对象并且接收方可以反序列化对象,您始终可以通过 I/O 流发送/接收对象。希望有帮助
First of all... why sending an object through I/O stream? What's wrong with XML?
However, you can always send/receive an object through I/O stream as long as the sender can serialize the object and the receiver can deserialize the object. Hope it helps
之一
您肯定需要查看以下两个库Google gson :http://code.google。 com/p/google-gson/
将 Java 对象转换为 JSON 并返回。优点是该对象可以由 Javascript 消费或生成。我也将其用于 Java-Java RPC,但如果您想稍后将浏览器定位到
Google 协议缓冲区,它可以为您提供灵活性: http://code.google.com/apis/protocolbuffers/
这就是 google 使用的 RPC。 Java、C、Python 的实现。如果您需要性能和最小的尺寸,那么这就是您的最佳选择(代价是您无法轻松查看数据来调试问题,就像使用 gson 一样,它会生成纯文本 JSON)。
You definitely need to look at one of these two libraries
Google gson: http://code.google.com/p/google-gson/
Converts Java object to JSON and back. advantage is that the object can be consumed or generated by Javascript. I have also used this for Java-Java RPC, but it gives you flexibility if you want to target browsers later
Google protocol buffers: http://code.google.com/apis/protocolbuffers/
This is what google uses for RPC. Implementations for Java, C, Python. If you need performance and the smallest size, this is the one to go with (The trade off is you can't look at the data easily to debug problems, like you can with gson, which generates plaint text JSON).