Tuesday, May 22, 2012

Socket input stream hangs on final read. Best way to handle this?

I'm a bit stumped on how to avoid my socket hanging on read. Here's my code:



    Socket socket = new Socket("someMachine", 16003);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
try {
outputStream.write(messageBuffer.toByteArray());
outputStream.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer response = new StringBuffer();
int result;
while ((result = in.read()) != -1) {
response.append(Character.toChars(result));
System.out.println(result);
}
System.out.println("Done!"); //never gets printed
} catch (...) {}


The above code successfully reads all the data from the stream but then hangs. Reading up on the net I was expecting to receive a -1 from the server (which I can't control) to indicate that I had reached the end of stream but instead I get this:



(Lots of data above this point)
57
10
37
37
69
79
70
10


It then hangs. So, my questions are:



1) Have I coded this wrong or is there an issue with the server's response?



2) If there is an issue with the server's response (i.e. no -1 being returned), how can I work around this (i.e. to stop reading when it hangs).



Any help appreciated!





No comments:

Post a Comment