开发者

Best way to send an ArrayList<String[]> over TCP in Java?

开发者 https://www.devze.com 2022-12-15 02:39 出处:网络
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开发者_Go百科 Strings).

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开发者_Go百科 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!


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.


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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消