简体   繁体   中英

How to send String array Object over Socket?

I have String array object. Lets say

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.

How to do it? Please help. Thanks.

You should create instance of Socket
get output stream and write to it (eg with 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 answer should be helpful for you

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

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

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.

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 restlet or Spring remoting are easy to set up.

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