3

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!

5 Answers 5

11

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.

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

2 Comments

+1 surely the first choice for a Java client/server solution
Thanks, I'll look in to that, much appreciated!
3

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

1 Comment

I'd avoid the GZIP stuff, though, unless you're on a low-bandwidth network and you have CPU cycles to burn.
1

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.

1 Comment

ah I've used JSON with Javascript before, might be a good choice thanks!
0

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.

1 Comment

Ah interesting, I'll take a look :)
0

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.

1 Comment

Thanks I'll research them both!

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.