Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中停止套接字中的while(true)_Java_Sockets_Serversocket - Fatal编程技术网

如何在Java中停止套接字中的while(true)

如何在Java中停止套接字中的while(true),java,sockets,serversocket,Java,Sockets,Serversocket,我正在使用Java套接字编程。当我第一次单击按钮时,插座工作正常。但是按钮和其他功能不再工作了。当我单击它们时,它们都被禁用或没有反应 这是主课 JButton btnRemote = new JButton("Remote "); btnRemote.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) {

我正在使用Java套接字编程。当我第一次单击按钮时,插座工作正常。但是按钮和其他功能不再工作了。当我单击它们时,它们都被禁用或没有反应

这是主课

JButton btnRemote = new JButton("Remote ");
        btnRemote.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                ServerInitiator ser=new ServerInitiator();
                ser.initialize(4444);
            }
        });
套接字类

 public static void main(String args[]){
        String port = JOptionPane.showInputDialog("Please enter listening port");
        new ServerInitiator().initialize(5555);
    }

    public void initialize(int port){

        try {
            ServerSocket sc = new ServerSocket(port);
            //Show Server GUI
            drawGUI();
           // drawGUI();
            //Listen to server port and accept clients connections
            while(true){
                Socket client = sc.accept();
                System.out.println("New client Connected to the server");
                //Per each client create a ClientHandler
                new ClientHandler(client,desktop);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

您应该将GUI与服务器逻辑分开。无论如何 您可以使ClientHandler成为可运行的,然后为每个新客户端生成一个新线程:

// server is listening
while (true){
...
new Thread(new ClientHandler(client, desktop)).start();
...
}

初始化应该在一个单独的线程中完成。在上面的上下文中什么是
ClientHandler
?你能分享一下吗?你指的是哪个“按钮其他功能”?在我看来,这个按钮只有一个功能,即生成一个
ServerInitiator
。当我意识到它是
JButton
而不是
button
时,我已经走了一半路了。您能为
Swing
AWT
添加标签吗?