Java swing GUI freezes

concurrency, java, sockets, swing, user-interface

Solution

You have two pitfalls in your design:

- `ss.accept()` is a blocking call so your UI will freeze until there is an incoming connection

- Never run `while(true)` loops in the EDT.

Instead do the following:

- When the button is clicked create a thread that will start listening for incoming connections.

- Whenever you have an incoming connection, create another thread that will take the incoming client connection and deal with it.

Problem

I am writing a Java client/server GUI application using sockets and here is the problem: I have a button to start listening for a specified port: button actionPerformed method ``` private void listenButtonActionPerformed(java.awt.event.ActionEvent evt) { int port = Integer.parseInt(portTextfield.getText(), 10); try { socket.listen(port); } catch (IOException ex) { } } ``` Here is the socket.listen method ``` public static void listen() throws IOException { ServerSocket ss = new ServerSocket(port); while (true) new socket(ss.accept()); } ``` "socket" class extends "Thread" So after ss.accept() returns a value it creates new socket instance in separate thread. After clicking the button the GUI freezes because inside the socket.listen method there is an infinite loop. How can I avoid that?

Original source

Related problems