I'm currently writing a client-server application with Java on the client side. When starting up the client, I start a thread that runs in the background and sends/receives data when the GUI asks for it. The GUI doesn't change anything in the network thread object, but sets a state in a "monitor" object that the network thread watches in a loop.
Now the problem is: when I constantly System.out.println() something in the client loop, the thread keeps running and sends/receives data as it should. But when I do not Sysout anything in that loop, the client loop stops and thus nothing happens when I attempt to send something to the server.
Here's the run()-method:
@Override
public void run() {
try {
srv_loop: while(true) {
System.out.println("Looping"); // When removing this line, it all breaks down and nothing happens when I attempt to send to the server.
if(!monitor.message.equals("")) {
if(monitor.message.equals("CLOSE")) {
break srv_loop;
}
outStream.writeInt(monitor.message.length());
System.out.println("Wrote length: " + monitor.message.length());
outStream.writeBytes(monitor.message + '\n');
System.out.println("Wrote message: " + monitor.message);
String answer = inStream.readLine();
System.out.println("Got answer: " + answer);
if(answer.equals("ACK")) {
monitor.message = "";
} else if(answer.equals("FAIL")) {
monitor.message = "FAIL";
}
}
}
} catch(IOException e) {
e.printStackTrace();
}
System.out.println("out");
}
Now I could of course leave the sysout there and it will work, but I don't want to have my terminal run amok all the time when I use my program. This seems so strange to me, I really have no clue why this happens. The only thing sysout does is to print and make a little delay, however Thread.sleep(100) does not work either.
I know I should have taken a more event-driven approach and that this is really not a good way to write a client in Java, but I only use Java to prototype -- Swing GUI works anywhere and that's all I need right now.
Thanks in advance.