• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Client side listening problem

 
Ravi Shankarappa
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have written a client that connects to a server on a tcp socket and waits for bytes to come in. The class implements Runnable. In the Run portion of the code I have a while loop and check to see if there are any available bytes in the DataInputStream and process them if they are present.

Problem is I have to do a "Thread.sleep(30)" in the loop or else the program hangs. With this sleep code in place, my program works fine in Windows but not in Linux. However if I increase the sleep time to 100 mSec then it works in Linux also. This just doesn't make sense. I think, although the code works with having a sleep in place, it might not be the way correct Java should be written for a client who is waiting for bytes.

So what is it thet I am doing wrong and how to code correctly for listening bytes coming in?

regards
Ravi
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You definitely should not have the sleep. Just read in a loop. The read call will block until there's data available. Usually this will be done in its own thread, so other parts of the app aren't blocked waiting for the read, and if it's a GUI app, you definitely should not do it in the GUI thread, otherwise you'll stop your GUI from responding to user actions and updating itself.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic