I have a server which initially does this:-
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
for (;;) {
String cmdLine = br.readLine();
if (cmdLine == null || cmdLine.length() == 0)
break;
...
}
later it passes the socket to another class "foo" This class wait for application specific messages.
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
appCmd=br.readLine();
My client sends this sequence:
- "bar\n"
- "how are u?\n"
- "\n"
- "passing it to foo\n"
- "\n"
The problem is that sometimes "foo" does not get its response. It hangs in the readLine()
.
What is the chance that readLine()
in the server is buffering up the data using the read ahead and "foo" class is getting starved?
If I add a sleep in the client side, it works. But what is the chance that it will always work?
- "bar\n"
- "how are u?\n"
- "\n"
sleep(1000);
- "passing it to foo\n"
- "\n"
How to fix the problem? Appreciate any help on this regard.
ready()
before you try to read it..do this inside the loop – Zygoteready() - tell whether this stream is ready to be read
. Usually, I use this together withread()
. I don't use it withreadLine()
e.g.:while(true) { if (br.ready()) { br.read(cb); cb.flip(); String msg = cb.toString(); if (msg == null) break; } }
cb is aCharBuffer
of a certain buffer size. This technique will allow reading a number of lines allowed in the buffer. – Zygote