Search code examples
javamultithreadingportserversocket

My GUI freezes after I recreate a ServerSocket


My Server is build around support to update the listening socket, by doing so I use the following method. my problem occurs after this method is called for the second time, this is first called at start up from the main method then later it is called by clicking a button in a JFrame. what happens is that the JFrame freezes when this method is called via button, as you can see by the code I tried to make this method run a server in a new thread but it hasn't changed my outcome. Does anyone know how to fix this? or at least what is causing it? also any code after the method is called in the main doesn't get execute, so I believe it is a thread problem. (MiniServer extends Thread and is used to handle each connected client individually)

public static void startListening(final int port)
{
    listeningThread = new Thread() 
    { 
        public void run()
        {               
            try {
                serverSocket = new ServerSocket(port);

                while(!stop)
                {
                    boolean loop = true;
                    while (loop)
                    {
                        serverSocket.setSoTimeout(1000);

                        try{
                            clientSocket = serverSocket.accept();
                            loop = false;
                        } catch (SocketTimeoutException e){
                        }
                    }
                    if(!clientSocket.equals(null))
                    {
                        MiniServer mini = new MiniServer(clientSocket);
                        mini.start();
                        clientSocket = null;
                    }
                }
            } catch (IOException e) {
            }
        } 
    };
    listeningThread.run();
}

Solution

  • You need to be calling listeningThread.start(), which will create a new thread. Right now, you're just calling the thread's run() method on the current thread. The first time you do that it works, since you're on the main thread. The second time, though, you're on the UI thread, reacting to the button press. This causes your UI thread to block.