简体   繁体   中英

Program freeze when calling Server method in Java

I have a basic GUI in Java where there is a JButton ,I have given a functionality to start the Server with that button. But when I click the button the program freezes. Is it because of the while loop ? If so how can I overcome this?

Server Code

 void connect_clients()
{
    try {
        ServerSocket listener = new ServerSocket(7700);
        try {
            while (true) {
                Socket socket = listener.accept();
                try {
                    PrintWriter out =
                            new PrintWriter(socket.getOutputStream(), true);
                    out.println(new Date().toString());
                }

                finally {
                    socket.close();
                }
            }
        }
        finally {
            listener.close();
        }
    }
    catch (IOException ex) {
        Logger.getLogger(Test_Frame.class.getName()).log(Level.SEVERE, null, ex);
    }   
}

Here is method explanation of ServerSocket.accept() :

Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.

Until there is data input to socket, your program will freeze. If it's another problem, please check your logs. There may be another problem.

Your program is freezing because you are blocking the UI thread. You need to post this on a separate thread:

public void postListen()
{
    new Thread(new Runnable()
    {
        public void run()
        {
            connect_clients();
        }

    }).start();
}

Call that method instead and it should run the connect_clients() method on a separate thread. The new thread will block until a client connects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM