0

Please help me out on how to read the stream of data in java. My requirement is to make the telnet connection to the router. This part is accomplished. From the router, Have to connect to the xxx remote machine using its ip address and port number through telnet. While making this connection, i am getting some response. But while reading, the program control stops at read() method of InputStream class. Here are the code snippet which i am using to read the stream of data.

        buff = new byte[4*1024];
        ret_read = 0;

        do
        {
           ret_read = in.read(buff); // Program control gets hanged here. Once all the data are read...
           if(ret_read > 0)
           {
               System.out.println(new String(buff,0,ret_read));

           }
        }while(ret_read > 0);

1 Answers1

1

What is happening is the read is blocking and waiting for more data to be sent on the stream, it will continue to do that until the stream is closed or more data is sent.

You need to either use a non-blocking read, put a timeout on the read, or close the stream server side after it finishes sending the data.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • Its waiting for some more data to read. But there is no data in the stream. So how to come out from the read() method. – Sathesh Subburaj Dec 17 '13 at 10:01
  • You can use available() to see if anything is there before trying to read or you can use a non blocking connection such as a socket channel: http://docs.oracle.com/javase/6/docs/api/java/nio/channels/SocketChannel.html – Tim B Dec 17 '13 at 10:08
  • Thanks Tim. But the available() method in InputStream Class always returns zero. So i will try with the non-blocking connection for read() – Sathesh Subburaj Dec 17 '13 at 10:10