1

Possible Duplicate:
Is it possible to read from a Java InputStream with a timeout?

I noticed that when I was trying to read in more information then was sent to my server, the web browser would freeze. I saw that my socket froze, since the web browser was returning less information then it was trying to read. Is there a way to set out a time out on Currtly I’m using a input stream

public String ReadLine()
 {
    String out;
    out="";
     // read in one line
     try{
         request = new StringBuffer(1000);
        boolean f=true;
        while(true)
        {
            int c=in.read();
            if (c=='\r') 
                {
                // next should be a \n
  // Program freezed hear
                 c=in.read();
                if (f==true)
                    return "";
                 break;
                }
            f=false;
            out=out+(char)c;

            request.append((char)c);
                } // end while

     } catch(IOException ec)
        {
            System.out.println(ec.getMessage());    
        }

        System.out.println(request);


    return out; 
 } 
Community
  • 1
  • 1
Ted pottel
  • 6,869
  • 21
  • 75
  • 134
  • could you please fix the formatting? Just select the program text and click the {} button. – alf Oct 19 '11 at 23:00

3 Answers3

6

Socket.setSoTimeout() or HttpURLConnection.setReadTimeout().

user207421
  • 305,947
  • 44
  • 307
  • 483
1

It was discussed here: Is it possible to read from a InputStream with a timeout?

As far as I can see, the solution is provided.

Community
  • 1
  • 1
alf
  • 8,377
  • 24
  • 45
  • Hi,thank you. I did Google the question and usually stack over flow will show up if it has a question with those keywords. – Ted pottel Oct 20 '11 at 13:42
-1

you have a couple of choices but it isn't pretty. the 'normal' java socket io doesn't have timeouts nor do the streams

  1. do your reading in a separate thread and queue up the input data with a timeout mechanism of your own

  2. use java nonblocking IO api

    http://download.oracle.com/javase/1.4.2/docs/guide/nio/

dmh2000
  • 683
  • 3
  • 7
  • 1
    Wrong. The 'normal' Java socket I/O has `Socket.setSoTimeout()` and `HttpURLConnection.setReadTimeout()`. Streams that aren't attached to sockets don't have any reason to timeout other than perhaps from the console. – user207421 Oct 19 '11 at 23:07