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.

Winn
  • 413
  • 2
  • 6
  • 17

3 Answers3

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

Community
  • 1
  • 1
Ilya
  • 29,135
  • 19
  • 110
  • 158
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); 
Ilya
  • 29,135
  • 19
  • 110
  • 158
Akkusativobjekt
  • 2,005
  • 1
  • 21
  • 26
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.

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162