aspose file tools*
The moose likes Sockets and Internet Protocols and the fly likes Client side listening problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Client side listening problem" Watch "Client side listening problem" New topic
Author

Client side listening problem

Ravi Shankarappa
Ranch Hand

Joined: Jan 09, 2010
Posts: 55
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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Client side listening problem