gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:13:16 25 4
gpt4 key购买 nike

我正在使用Java 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();
}
}

最佳答案

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

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

关于java - 如何在Java中停止socket中的while(true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18318327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com