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!
I think you will only get -1 when the server decides to stop the conversation, i.e. closes its output stream or closes the socket completely. Else, the stream stays open for potential future incoming data.
I'm not a Android expert, but this seems to work just fine on Android:
try {
telnetClient = new Socket(server, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (telnetClient.isConnected()) {
try {
InputStream instr = telnetClient.getInputStream();
int buffSize = telnetClient.getReceiveBufferSize();
if (buffSize > 0) {
byte[] buff = new byte[buffSize];
int ret_read = instr.read(buff);
screen.append(new String(buff, 0, ret_read));
}
} catch (IOException e) {
screen.append("Exception while reading socket:" + e.getMessage());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With