I have an Android app that communicates over a TCP socket with a server I wrote. The method I’m using now to read and write output works fine for smaller strings (up to 60kB) but I get an exception thrown when the string is much longer than that. Here is the relevant part of what I have for the server and client:
Server:
DataInputStream dis = null;
DataOutputStream dos = null;
try {
dis = new DataInputStream(server.getInputStream());
dos = new DataOutputStream(server.getOutputStream());
String input = "";
input = dis.readUTF();
handle_input info = new handle_input(input, id);
String xml = info.handle();
dos.writeUTF(xml);
server.close();
}
Client:
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
Boolean result;
try {
socket = new Socket(ip, port);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
dos.writeUTF(the_text);
String in = "";
while (in.equals("")) {
in += dis.readUTF();
}
}
How can I modify it to deal with potentially enormous Strings? I’ve been looking around and can’t seem to find a clear answer.
Thanks.
If you look at the javadoc for
writeUTF(), it is obvious that the method can only handle strings with up to 65535 encoded bytes. (The encoded form starts with 2 bytes that give the string byte count).Your choices are:
String.toCharArray(),All of these will entail preceding the actual data with a count to tell the other end how much to expect / read.
The other approach is to send/receive the data as text using a
WriterandReaderinstead ofDataOutputStreamandDataInputStream.