Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sockets

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!

like image 957
Chris Knight Avatar asked Feb 03 '11 12:02

Chris Knight


2 Answers

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.

like image 63
JB Nizet Avatar answered Sep 21 '22 13:09

JB Nizet


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());
        }
    }
like image 34
Norberto Bezi Avatar answered Sep 22 '22 13:09

Norberto Bezi