views:

348

answers:

5

Hello,

I'm writing a client/server application in Java and I'm using TCP to transfer data which I'm storing in an ArrayList (i.e. An ArrayList of arrays of Strings).

What is the best way to transfer that data from one to the other? Should I make one long string and use a PrintWriter's println() or is there a better way?

Thanks very much!

A: 

Many people would use a web service framework for this, such as Apache CXF. You could also go one level down to JAXB or XML Beans.

bmargulies
Ah interesting, I'll take a look :)
Danny King
+7  A: 

Assuming both client and server and written in Java, and assuming you're stick with raw sockets, rather than a higher-level remoting framework:

OutputStream socketStream = ... 
ObjectOutput objectOutput = new ObjectOutputStream(socketStream);
objectOutput.writeObject(myDataList);

Similarly, use ObjectInputStream at the receiving end.

Should work nicely, as long as everything inside the list implements java.io.Serializable.

skaffman
+1 surely the *first* choice for a Java client/server solution
Brian Agnew
Well RMI would be my first choice....
skaffman
Thanks, I'll look in to that, much appreciated!
Danny King
A: 

You might want to consider the JSON framework. See json.org. JSON = Javascript Object Notation. Even though the name suggests the use of Javascript, the json.jar is a good serialization/deserialization tool.

M Cooper
ah I've used JSON with Javascript before, might be a good choice thanks!
Danny King
A: 

You may want to look into Serialization. You could just make up your own format for such a simple case, though. Personally I favour bencoding. The minimum effort (and least bug-prone) solution here is Serialization, though.

ZoFreX
Thanks I'll research them both!
Danny King
+3  A: 

To add a bit to skaffman's answer:

OutputStream socketStream = ... 
GZIPOutputStream objectOutput = new GZIPOutputStream(new ObjectOutputStream(socketStream));
objectOutput.writeObject(myDataList);

And on the client:

InputStream socketStream = ...
ObjectInputStream objectInput = new ObjectInputStream(new GZIPInputStream(socketStream));
ArrayList<type> a = objectInput.readObject();
Chinmay Kanchi
Thanks that helps!
Danny King
I'd avoid the GZIP stuff, though, unless you're on a low-bandwidth network and you have CPU cycles to burn.
skaffman