4

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.

1

3 Answers 3

6

You should create instance of Socket
get output stream and write to it (e.g. 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

Sign up to request clarification or add additional context in comments.

Comments

2

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); 

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.