how to read using InputStreamReader without blocking
Is there a simple w开发者_C百科ay to turn the standard code:
in = new InputStreamReader(socket.getInputStream());
String message = "";
while ((size = in.read(buf)) != -1){
message += new String(buf, 0, size);
}
so that read()
won't block. I tried doing:
if (!in.ready())
//throw exception
but this throws an exception all the time. Maybe:
socket.setSoTimeout(120000);
in = new InputStreamReader(socket.getInputStream());
but this, as stated by everyone below, doesn't work. Other ideas?
Depending on which kind of InputStream is backing your reader and if you are using a fixed-length character encoding for the reader, you may be able to use the available method on the backing stream. For most implementations of InputStream, available()
will return the number of bytes you can read without blocking. If the character encoding uses a fixed number of bytes per character, you know how much you can read from the InputStreamReader without blocking.
To "prevent blocking" either...
1) Use NIO (which requires the use of Channels underneath); or a nicer wrapper about NIO use as MINA, XNIO, xSocket, etc. I do not recommend using NIO directly as there are a number of issues to deal with.
2) Use threads; make sure to employ standard thread-data isolation rules to avoid headaches. Concurrency-aware data-structures such as ConcurrentLinkedQueue are your friends.
setSoTimeout does not prevent blocking; it merely adds a timeout to blocking operations. I avoid it because of the numerous "quirks" it has. Use at your own risk.
精彩评论