julivico julivico - 6 months ago 28
Java Question

Socket client: don't get the full response with DataInputStream.readUTF()

I want to write a socket client to send a request to a server and get response back. It works, but not right.
Here is my code:

public String send(final String data) {
Socket client = null;
String response = null;

try {
client = new Socket(this.host, this.port);

final OutputStream outToServer = client.getOutputStream();
final DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(data);

final InputStream inFromServer = client.getInputStream();
final DataInputStream in = new DataInputStream(inFromServer);
response = in.readUTF();
} catch (final IOException e) {
this.log.error(e);
this.log.error("Sending message to server " + this.host + ":" + this.port + " fail", e);
} finally {
if (client != null) {
try {
client.close();
} catch (final IOException e) {
this.log.error("Can't close socket connection to " + this.host + ":" + this.port, e);
}
}
}
if (StringUtils.isBlank(response)) return null;
return response;
}


The problem is: I didn't got the full response with
in.readUTF()
. I always got a response with the same length as the sent data's length (variable
data
). I have tested with other GUI client and got the full response. So it's not a problem of the server.
Does someone known, what i did wrong?

UPDATE

Thanks EJP and Andrey Lebedenko. I think, my problems are the functions
writeUTF
and
readUTF
. So i have edited my code in the
try
block so:

Charset charset = Charset.forName("ISO-8859-1");
final OutputStream outToServer = client.getOutputStream();
final DataOutputStream out = new DataOutputStream(outToServer);
out.write(data.getBytes(charset));

final InputStream inFromServer = client.getInputStream();
final BufferedReader in = new BufferedReader(new InputStreamReader(inFromServer, charset));
response = in.readLine();


And it worked now.

EJP EJP
Answer

If it works with Telnet, as per your comment, the server isn't using readUTF(), so your writeUTF() is already wrong, and the server is therefore unlikely to be using writeUTF() either, which would make your readUTF() wrong as well. You can't use these methods arbitrarily: they can only interchange data between themselves.

I'll bet your GUI client that works doesn't use them either.