Java - Threads, Swing, and ServerSocket

后端 未结 2 848
面向向阳花
面向向阳花 2021-01-14 22:10

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

相关标签:
2条回答
  • 2021-01-14 22:24

    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.

    0 讨论(0)
  • 2021-01-14 22:33

    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.

    0 讨论(0)
提交回复
热议问题