BufferedReader.readline() behavior with Sockets

O

oziris

hi !

Here the piece of code that creates my BufferedReader object

--- code ---
Socket socket = new Socket(....);
BufferedReader inSocket =
new BufferedReader(
new InputStreamReader(
m_socketService.getInputStream()));
--- /code ---

My request concerns the method readline() of this object. According to
what I understood of my readings, I expect from this method it blocks
itself until data comes to the socket.

Is that correct? Because in my implementation, this method returns
always null if there is no data to read. So I have to write this

--- code ---
String requete;
if ((requete = inSocket.readLine()) != null)
{
// do something
}
--- /code ---

And that sounds bad to me. It's like an infinite loop...

Thanks a lot for your precious advices.

-o--
 
N

NullBock

Calling InputStream#read() (which the BufferedReader ultimately does)
blocks until there is data to be had, *or* the stream closes. So your
code is proper, and isn't an infinite loop. I'd write it so:

BufferedReader r;
//...
String s;
while ((s = r.readLine()) != null) {
//do something
}

This is not only acceptable, but necessary. Once the stream closes,
BufferedReader returns null. That is, unless the stream doesn't close
cleanly, either because it becomes corrupted or interrupted. In that
case, readLine() simply throws an exception.


Walter Gildersleeve
Freiburg, Germany

______________________________________________________
http://linkfrog.net
URL Shortening
Free and easy, small and green.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top