Hello,
I am looking for a good sollution for implementation of timeouts in BufferedReader. I use HTML parser with callbacks for parsing HTML and sometimes it hangs forever due to server timeouts at the server side. So i need a timeout built in BufferedReader to interrupt hanged parsing. I found this sollution, but it is not good for networking:
import java.io.BufferedReader;
import java.io.IOException;
public class TimedBufferedReader extends BufferedReader {
private int timeout = 0;
BufferedReader in;
/**
* TimedBufferedReader constructor.
* @param in java.io.Reader
*/
TimedBufferedReader(java.io.Reader in) {
this(in,1024);
}
/**
* TimedBufferedReader constructor.
* @param in java.io.Reader
* @param sz int Size of the input buffer.
*/
TimedBufferedReader(java.io.Reader in, int sz) {
super(in, sz);
this.in=(BufferedReader)in;
}
/**
* Sets number of seconds to block for input.
* @param seconds int
*/
public void setTimeout(int millyseconds) {
timeout=millyseconds*10;
}
public int read(char buf[]) throws IOException
{
int msec = 0;
while (!this.in.ready()) {
try { Thread.currentThread().sleep(100); }
catch (InterruptedException e) { break; }
msec+=100;
if (this.in.ready()) return this.in.read(buf);
if (msec >= timeout)
{
throw new IOException("Timeout for reading");
}
}
return this.in.read(buf);
}
}
I modified this several times and none of my modifications worked for HTML parsing with callbacks. It allways gives timeout. Even if it founds good URL.
Please kindly help.
Thanks in advance,
F.