如何在Java中的socket中停止while(true)

时间:2013-08-19 16:09:46

标签: java sockets serversocket

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

这是主类

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();
        }
    }

1 个答案:

答案 0 :(得分:1)

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

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