Starting ServerSocket on Java with User Interface(Swing) Freezes

…衆ロ難τιáo~ 提交于 2019-11-27 16:30:18

Swing is a single threaded framework, meaning any blocking or long running operation executed within the context of the Event Dispatching Thread will prevent it from processing the Event Queue, making your application hang.

It's also not thread safe, so you should never try and modify the state of any UI component from out side of the EDT.

Take a look at Concurrency in Swing and Worker Threads and SwingWorker for more details

public class ServerSocketWorker extends SwingWorker<Void, String> {

    private JTextArea ta;

    public ServerSocketWorker(JTextArea ta) {
        this.ta = ta;
    }

    @Override
    protected void process(List<String> chunks) {
        for (String text : chunks) {
            ta.append(text);
        }
    }

    @Override
    protected Void doInBackground() throws Exception {
        ss = new ServerSocket(1234, 3);
        while (true) {
            publish("\nEsperando conexiones...");
            Socket s = ss.accept();
            publish("\nConexión entrante: " + s.getRemoteSocketAddress());

            conexiones++;
            //System.out.println("Debug: conexiones SERVER: " + conexiones);
            MultiThread mt = new MultiThread(s, conexiones);
            mt.start();
            ///////////////////////////////////////////////////////////////
        }
    }

    @Override
    protected void done() {
        stopServer(); //??
    }
}

To start it, you could use something like...

public void iniciarServer() {
    ServerSocketWorker worker = new ServerSocketWorker(textAreaToAppendTo);
    worker.execute();
}

As an example

The method ServerSocket.accept() is a blocking method. This means that Socket s = ss.accept(); stops the current thread until a connection to the server socket is opened.

Event dispatching in Swing is single threaded, the while loop and the blocking operation mentioned above, will keep the thread 'busy' and block all other interactions with the UI.

You should run your entire while loop in a separate thread. When you want to stop the server, you should also ensure that the while loop is exited and the thread completes execution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!