简体   繁体   English

在Java中调用Server方法时程序冻结

[英]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. 我在Java中有一个基本的GUI ,其中有一个JButton ,我提供了使用该按钮启动Server的功能。 But when I click the button the program freezes. 但是,当我单击按钮时,程序将冻结。 Is it because of the while loop ? 是因为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() : 这是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. 您的程序被冻结,因为您正在阻止UI线程。 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. 而是调用该方法,它应该在单独的线程上运行connect_clients()方法。 The new thread will block until a client connects. 新线程将阻塞,直到客户端连接为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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