Reputation: 1991
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!
Upvotes: 3
Views: 5682
Reputation: 11
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.
Upvotes: 1
Reputation: 65903
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();
Upvotes: 3
Reputation: 8920
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.
Upvotes: 0
Reputation: 403481
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
.
Upvotes: 11
Reputation: 100050
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.
Upvotes: 0