I know I know, already a million questions and answers on this everywhere. Tons of really detailed articles on it, several types of examples. I\'ve spent the past few hours
You are reading from your Socket on the EDT. This means that you block it. Calling invokeLater only causes your Runnable to be executed on the EDT. You are piling two calls on the EDT, one of them being your socket.
Consider moving your socket in a SwingWorker which returns progressively the values of your Socker to the GUI.
Socket operations block. For instance, if you call accept
, the call will not return until someone actually connects to your program, effectively blocking the thread it's running on. That's why they suggest to have the networking run on a secondary thread.
In your case, you do create a thread, but you don't call accept
from it.
while(true) {
try {
// this is called on the EDT--beware!
network.setSocket(network.getServerSocket().accept());
AddUser(network.getSocket());
// ... and then, everything called from x will be on the secondary thread
Thread x = new Thread(network);
x.start();
} catch (Exception e) {
System.out.println("Failed to connect.");
}
}
This is why it freezes. The call to accept
must be done from the secondary thread if you don't want to block the UI.