Question

In most Java client/server examles they use ServerSocket.accept() method to receive messages from the client. This method blocks the thread. This looks good becouse server does not do useless work and can answer immediately. But on the client side they use infinite loop like this:

BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
    String cominginText = "";
    try
    {
        cominginText = in.readLine ();
        System.out.println (cominginText);
    }
    catch (IOException e)
    {
        //error ("System: " + "Connection to server lost!");
        System.exit (1);
        break;
    }
}

This looks bad because in my mind client does useless work. Is there some way to receive a message on the client side without doing useless work and immediately like on server side (may be should use listeners?)

"What do you mean by useless work? – Braj 31 mins ago "

for example checking in loop is button pressed (we should use listener)

while (!button.isPressed() ) { } is bad way.

Was it helpful?

Solution

There is no 'useless work' here, as the socket is in blocking mode, but there is:

  1. A pointless initialization of 'comingText'.
  2. A failure to check it for null, so it will spin mindlessly at EOS.
  3. An incorrect handling of IOExceptions: not all of them are fatal, e.g. SocketTimeoutException, and none of them should cause an immediate System.exit().
  4. The line read is thrown away, which is an application protocol error.

So it is definitely wrong.

OTHER TIPS

in.readLine() blocks. The loop wont continue until a String returns

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top