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.