Search code examples
javastringsocketsinputstreambufferedreader

StringBuffer is not been printed correctly


I am trying to read some data from a InputStream, and then put them into a StringBuffer to print it.

I put this code in the main method.

My problem is that the StringBuffer is only printed when I am debugging the code, when I run it normally it isnt been printed.

My code:

Socket s = new Socket();
String host = "";
PrintWriter s_out = null;
BufferedReader s_in = null;
InputStream in = null;

s.connect(new InetSocketAddress(host, 23));

//writer for socket
s_out = new PrintWriter(s.getOutputStream(), true);
//reader for socket
s_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
in = s.getInputStream();

if(s.isConnected() == true && s.isInputShutdown() == false && s.isOutputShutdown() == false){
    StringBuffer sb = new StringBuffer();
    boolean found = false;
    char ch;
    int numberOfBytesThatCanBeRead = in.available();

    for(int j = 0; j < numberOfBytesThatCanBeRead; j++){
        ch = (char) s_in.read();
        //System.out.print(ch);
        sb.append(ch);
    }

    System.out.print(sb.toString());

    s_in.close();
    in.close();
    s_out.close();
    s.close();

The correct value of this variable is 564, but it is only returned when I debug the code, when i run normally it returns 21.

int numberOfBytesThatCanBeRead = in.available();

So, my question is: Why when I debug the code, the result of StringBuffer is correct, and when I run normally it is not ?

Thanks !


Solution

  • You have no loop listening on the port, that means that you run through and end immediately before the other side has finished sending all its data.

    When you debug that means there is enough time for it all to arrive before you try and read it.

    Do the reading in a loop waiting until all the data you need has arrived.