Java 如何通过套接字发送字符串数组对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19786202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:12:37  来源:igfitidea点击:

How to send String array Object over Socket?

javasockets

提问by Winn

I have String array object. Lets say

我有 String 数组对象。可以说

String[] names = new String[7];

And I am also making this object persistent by storing it into file using ObjectOutputStream on my client system. I am reading the stored object using ObjectInputStream. Upto this Okay. Now I want to send this object to another system over socket.

我还通过在我的客户端系统上使用 ObjectOutputStream 将它存储到文件中来使这个对象持久化。我正在使用 ObjectInputStream 读取存储的对象。到此为止。现在我想通过套接字将此对象发送到另一个系统。

How to do it? Please help. Thanks.

怎么做?请帮忙。谢谢。

采纳答案by Ilya

You should create instance of Socket
get output streamand write to it (e.g. with ObjectOutputStream).

您应该创建Socket 的实例
获取输出流并写入它(例如使用ObjectOutputStream)。

Socket echoSocket = new Socket(hostName, portNumber);
ObjectOutputStream out = new ObjectOutputStream(echoSocket.getOutputStream());
out.writeObject(names);  

You can find an example in Oracle docs: example.
Also this answershould be helpful for you

您可以在 Oracle 文档中找到一个示例:example
另外这个答案应该是对你有帮助

回答by Mariusz Jamro

To answer your question: in Java Array and String are serializable types, so array of strings can be converted to string (!), send over network and than deserialized (converted back to object). See: How to serialize object in java, but instead of doing that i suggest converting your data to xml, json or any other transport data format and than sending it as string. This would save you lot of trouble.

回答您的问题:在 Java 中 Array 和 String 是可序列化类型,因此字符串数组可以转换为字符串(!),通过网络发送而不是反序列化(转换回对象)。请参阅:如何在 java 中序列化对象,但我建议将您的数据转换为 xml、json 或任何其他传输数据格式,而不是将其作为字符串发送,而不是这样做。这会为你省去很多麻烦。

To go even further - instead of sending data that at very low level (sockets, streams, etc.) I would suggest creating higher level service and calling it via http. Frameworks like restletor Spring remotingare easy to set up.

更进一步 - 而不是发送非常低级别的数据(套接字、流等),我建议创建更高级别的服务并通过 http 调用它。像restletSpring 远程处理这样的框架很容易设置。

回答by Akkusativobjekt

A String Array object implements the Serializable interface, therefore it can be send over a network as byte stream :

String Array 对象实现了 Serializable 接口,因此它可以作为字节流通过网络发送:

Socket socket = new Socket(host, port);
ObjectOutputStream outputStream = new ObjectOutputStream(
                socket.getOutputStream());
String[] names = new String[1]; // Empty at the moment
outputStream.writeObject(names);