0

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.

osseum
  • 187
  • 14
  • 1
    Doesn't `in.readLine()` block as well on the client side? – mellamokb Apr 09 '14 at 21:45
  • `ServerSocket.accept()` method is not used to receive messages from client. Its waiting for someone to accept the socket. Input/Output Streams are used for message communication. – Braj Apr 09 '14 at 21:49
  • What do you mean by `useless work`? – Braj Apr 09 '14 at 21:51

2 Answers2

0

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

Vince
  • 14,470
  • 7
  • 39
  • 84
0

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.

user207421
  • 305,947
  • 44
  • 307
  • 483