views:

496

answers:

2

Is there a simple way 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?

+1  A: 

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.

jarnbjo
+2  A: 

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.

pst
Or the new asynchronous API (part of "More NIO Features") in JDK7.
Tom Hawtin - tackline
1- it sounds like that's an external package. If so, I'll try to solve the problem without external packages2- I'm already using threading
Guy