Forums Register Login

While loop problem

+Pie Number of slices to send: Send
Hi all,

Greenhorn here, would appreciate your kind assistance very much.

This code was from "Java head first 2nd edition, chapter 15, simple chat client".

The book creates the following sub class of Runnable:



(reader is an instance of BufferedReader used here to receive Strings from a server)

It is then placed in a thread:



A server is set up separately. It sends Strings to clients running the above code whenever it receives code from one of its clients (group chat program).

I've been trying to figure out why the JVM doesn't exit the while loop and subsequently kill the thread when clients are not sending Strings, tried out the following:

1. Checked if reader.readLine() returned null when the server was not sending Strings.

>>> Result: reader.readLine() never seemed to return null.

2. However, line 6 wasn't executing continuously. So i added the following just before line 6:

>>> Result: while loop ran only when the client received a string from the server.

3. Tested while loops and read up abit, thinking that it may not be the while loop though still can't figure out why the thread isn't killed yet line 6 (line 84 below) doesn't get executed continuously. Much appreciate any assistance.

The complete code is as follows:





+Pie Number of slices to send: Send
reader.readLine() will return if there is no more data, and it knows no more data will come. The latter part is important in networking; the only way to ensure that no data will come is to close the connection. After all, on an open connection any data can still be sent.
+Pie Number of slices to send: Send
 

Rob Spoor wrote:reader.readLine() will return if there is no more data, and it knows no more data will come. The latter part is important in networking; the only way to ensure that no data will come is to close the connection. After all, on an open connection any data can still be sent.



Mr Spoor, thanks for your reply.

Does this mean that the JVM will pause at the readLine() method until either data comes in or the connection is closed?

Thanks all
+Pie Number of slices to send: Send
It's even a bit worse. It doesn't pause until data comes in - it pauses until a line break comes in or the stream ends, whichever comes first.
+Pie Number of slices to send: Send
K got it, thanks again!
+Pie Number of slices to send: Send
And welcome to the Ranch
roses are red, violets are blue. Some poems rhyme and some are a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1125 times.
Similar Threads
Seems like I can't read from a scoket?
Best way for login authentication
I need help improving this chat server and chat client!
How do you formally disconect a client from a server?
Usability features
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 05:56:39.