baseman101
baseman101

Reputation: 362

Java inputStream to String Hangs

I am developing a tool to get client information, send to a server, and receive the information again (a proxy). I'm also trying to dump the data being received from the server. I can read the Integer representation of the inputStream, but I am not able to read the String format. I've tried the below example, but it hangs and never connects to the server. Also, System.out.println(inputStream.nextLine()) displays only one line and hangs.

public void run() {
   try {
       int i;
       while ((i = inputStream.read()) != -1){
           System.out.println(IOUtils.toString(inputStream));
           outputStream.write(i);
       }
   } catch (IOException e) {
       System.out.println("Lost connection to the client.");
   }
}

Upvotes: 1

Views: 3028

Answers (2)

user207421
user207421

Reputation: 310860

  1. The code you posted doesn't attempt to connect to the server, but if any of it executes you must already have connected.
  2. If your program is hanging in this code, either the server hasn't sent any data yet, or the IOUtils.toString() method probably tries to read to EOS, so if the peer doesn't close the connection you will block here forever.
  3. If your program hangs at a readLine() call it means the peer hasn't sent a line to read.

Upvotes: 1

axiopisty
axiopisty

Reputation: 5137

My guess at this is that you're reading from the input stream, and then using the IOUtils library to read from the stream too. My suspicion is that your application is reading the first byte from the input stream, then reading the remainder of the inputstream with the IOUtils library, and then printing out the initial byte that was read.

It doesn't make any sense to call IOUtils.toString(inputstream) from within a loop. That method call will put all the data from the inputstream into a string. Why have the loop at all in this case?

You might want to try not using the IOUtils library for this. Just read a byte of data, push it into a StringBuilder, and then print that byte. In this approach, the loop would be necessary, and you'll probably get what you're looking for.

Try something like this, but modify it as necessary to print the data at the same time to your output stream:

public static String inputStreamToString(final InputStream is, final int bufferSize)
{
  final char[] buffer = new char[bufferSize];
  final StringBuilder out = new StringBuilder();
  try {
    final Reader in = new InputStreamReader(is, "UTF-8");
    try {
      for (;;) {
        int rsz = in.read(buffer, 0, buffer.length);
        if (rsz < 0)
          break;
        out.append(buffer, 0, rsz);
      }
    }
    finally {
      in.close();
    }
  }
  catch (UnsupportedEncodingException ex) {
    /* ... */
  }
  catch (IOException ex) {
      /* ... */
  }
  return out.toString();
}

Upvotes: 1

Related Questions